编写时间:2017/12/28
先介绍一下环境。我用的是vs2017,SQL server2017,浏览器火狐和Microsoft edge,其他的浏览器应该也行。涉及到的技术有c#,js(jQuery),Ajax,xml,除c#建议在微软技术文档中心学习外,其它的都可以在w3school进行简单的学习。下面正式开始。本实验的目的是创建商品信息的编辑页面。下图是文件结构:
目的是在浏览器实现商品信息的增加,修改,删除。数据传输的方式是Ajax、wbeservice,拒绝使用表单提交数据,因为这中页面用表单提交总是要不断地刷新的,体验不好。
首先创建客户端HTML页面,我用的是c#web窗体页面,文件名为Default.aspx,代码如下(用了一点vs的控件,比较简单不多说):
首先创建客户端HTML页面,我用的是c#web窗体页面,文件名为Default.aspx,代码如下(用了一点vs的控件,比较简单不多说):
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
销售表
序号
姓名
性别
生日
生产编号
数量
价格
操作
然后在APP_Code文件下创建Class1.cs文件,用来编写自己的c#类,将类写在一个单独的文件中我认为是一个好习惯。介绍一下MyClass_1.GetData()方法,该方法的第一步是创建datatable对象;第二步是从数据库中取出数据,并附加到datatable中,第三步是将datatable中的数据读出,并使之成为符合HTML/xml格式的字符串,这个字符串就是本方法要return(返回)的内容——一个table表。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Text;
using System.Web.Services;
using System.Xml.Serialization;
///
/// Class1 的摘要说明
///
namespace myclass
{
public class MyClass_1
{
public static string GetData()
{
SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-USCN62E\SQLEXPRESS;Initial Catalog=last;Integrated Security=True");
string sql = "select * from goods";
SqlCommand cmd = new SqlCommand(sql, conn);
DataTable table = new DataTable("goods");
table.Columns.Add("ID");
table.Columns.Add("姓名");
table.Columns.Add("性别");
table.Columns.Add("生日");
table.Columns.Add("生产编号");
table.Columns.Add("数量");
table.Columns.Add("价格");
table.Columns.Add("编辑");
table.Columns.Add("删除");
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//reader.GetOrdinal("id")是得到ID所在列的index,
//reader.GetInt32(int n)这是将第n列的数据以Int32的格式返回
//reader.GetString(int n)这是将第n列的数据以string 格式返回
int id = reader.GetInt32(reader.GetOrdinal("ID"));
string name1 = reader.GetString(reader.GetOrdinal("NAME1"));
string sex = reader.GetString(reader.GetOrdinal("SEX"));
string birthday = reader.GetString(reader.GetOrdinal("BIRTHDAY"));
int productid = reader.GetInt32(reader.GetOrdinal("PRODUCTID"));
int quantity = reader.GetInt32(reader.GetOrdinal("QUANTITY"));
double price = reader.GetDouble(reader.GetOrdinal("PRICE"));
table.Rows.Add(id, name1, sex, birthday, productid, quantity, price, "编辑", "删除");
}
reader.Close();
conn.Close();
//获取datatable中的内容并输出为HTML/xml字符串
StringBuilder strHTMLBuilder = new StringBuilder();
strHTMLBuilder.Append(" 销售表 ");
strHTMLBuilder.Append("");
foreach (DataColumn myColumn in table.Columns)
{
strHTMLBuilder.Append("");
strHTMLBuilder.Append(myColumn.ColumnName);
strHTMLBuilder.Append(" ");
}
strHTMLBuilder.Append(" ");
int j = 100;
foreach (DataRow myRow in table.Rows)
{
int i = 0;
strHTMLBuilder.Append("");
foreach (DataColumn myColumn in table.Columns)
{
strHTMLBuilder.Append("");
if(i == 7) { strHTMLBuilder.Append(" 编辑"); }
else if(i == 8) { strHTMLBuilder.Append("删除"); }
else { strHTMLBuilder.Append(myRow[myColumn.ColumnName].ToString()); }
strHTMLBuilder.Append(" ");
i++;
}
strHTMLBuilder.Append(" ");
j++;
}
strHTMLBuilder.Append("
");
string Htmltext = strHTMLBuilder.ToString();
return Htmltext;
}
}
}
这个方法的第一次调用是在Default.aspx.cs中的Page_Load中,代码和实现的表格效果如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using myclass;
public partial class _Default : System.Web.UI.Page
{
//页面加载时提取数据库中的记录并添加到表格中
protected void Page_Load(object sender, EventArgs e)
{
string a = MyClass_1.GetData();
div1.InnerHtml = a;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using myclass;
using System.Data;
using System.Text;
using System.Data.SqlClient;
///
/// WebService 的摘要说明
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
//[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
public WebService()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string HelloWorld(string x, string y, string a, string b, string c, string d, string e, string f)
{
string name1 = a;
string sex = b;
string birthday = c;
Int64 productid = Convert.ToInt64(d);
Int64 quantity = Convert.ToInt64(e);
double price = Convert.ToDouble(f);
if (x == "1")
{
DateTime dt = DateTime.Now;
int id = Convert.ToInt32(dt.ToString("ddHHmmss"));
//连接数据库
SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-USCN62E\SQLEXPRESS;Initial Catalog=last;Integrated Security=True");
string sql = "insert into goods (ID, NAME1, SEX, BIRTHDAY, PRODUCTID, QUANTITY, PRICE) values ('" + id + "', '" + name1 + "', '" + sex + "', '" + birthday + "', '" + productid + "', '" + quantity + "', '" + price + "')";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
if (x == "2")
{
int id = Convert.ToInt32(y);
//连接数据库
SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-USCN62E\SQLEXPRESS;Initial Catalog=last;Integrated Security=True");
string sql = "update goods set NAME1 = '" + name1 + "', SEX = '" + sex + "',BIRTHDAY = '" + birthday + "', PRODUCTID = '" + productid + "', QUANTITY = '" + quantity + "', PRICE = '" + price + "' where ID ='" + id + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
string answer = MyClass_1.GetData().ToString();
return answer;
}
[WebMethod]
public string DoSome(string x)
{
int id = Convert.ToInt32(x);
//连接数据库
SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-USCN62E\SQLEXPRESS;Initial Catalog=last;Integrated Security=True");
string sql = "delete from goods where ID = '" + id + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
string answer = MyClass_1.GetData().ToString();
return answer;
}
}
//将表格中的内容搬运到表单中
'use strict';
$(".edit").live("click",function (e) {
$("#Button5").attr('disabled',true);
var Like = $(e.target).parent().attr("id"); //通过e.target获取被点击的元素,与this不同
var idLike = Like.substring(0, 10); // 从索引0开始到8(不包括8)
var idLike0 = idLike + "0";
var idLike1 = idLike + "1";
var idLike2 = idLike + "2";
var idLike3 = idLike + "3";
var idLike4 = idLike + "4";
var idLike5 = idLike + "5";
var idLike6 = idLike + "6";
document.getElementById("editId").value = document.getElementById(idLike0).innerText;
document.getElementById("TextBox2").value = document.getElementById(idLike1).innerText;
var radio_1 = document.getElementById("RadioButton1");
var radio_2 = document.getElementById("RadioButton2");
if (document.getElementById(idLike2).innerText === "男") {
$(radio_1).attr("checked", "checked");
}
if (document.getElementById(idLike2).innerText === "女") {
$(radio_2).attr("checked", "checked");
}
document.getElementById("TextBox4").value = document.getElementById(idLike3).innerText;
document.getElementById("TextBox5").value = document.getElementById(idLike4).innerText;
document.getElementById("TextBox6").value = document.getElementById(idLike5).innerText;
document.getElementById("TextBox7").value = document.getElementById(idLike6).innerText;
});
function myfunc(x) {
$("#Button5").attr('disabled', false);
var y = $("#editId").val();
var a = $("#TextBox2").val();
var b;
if ($("#RadioButton1").attr("checked") == true) {
b = "男";
}
if ($("#RadioButton2").attr("checked") == true) {
b = "女";
}
var c = $("#TextBox4").val();
var d = $("#TextBox5").val();
var e = $("#TextBox6").val();
var f = $("#TextBox7").val();
$.ajax({
url: "WebService.asmx/HelloWorld", //发送到本页面后台AjaxMethod方法
type: "POST",
dataType: "text/xml",
async: true, //async翻译为异步的,false表示同步,会等待执行完成,true为异步
//contentType: "application/json; charset=utf-8", //不可少
data: {
x: x,
y: y,
a: a,
b: b,
c: c,
d: d,
e: e,
f: f
},
success: function (data) {
//将返回的xml信息转义
var str = data;
var reg = //g;
str = str.replace(reg, '>');
reg = /&/g;
str = str.replace(reg, '&');
reg = /'/g;
str = str.replace(reg, "'");
reg = /"/g;
str = str.replace(reg, '"');
var myStr = "销售表 ID 姓名 性别 生日 生产编号 数量 价格 编辑 删除 ";
var z = $(str).find("tr");
for (var i = 1; i < z.length; i++) {
myStr += "";
var v = $(z[i]).find("td");
for (var j = 0; j < v.length; j++) {
var text, attri, attribu;
if (j == 7 || j == 8) {
attri = v[j].getAttribute("id");
text = $(v[j]).find("span").text();
attribu = $(v[j]).find("span").attr("class");
myStr += "";
myStr += text;
myStr += " ";
} else {
text = v[j].childNodes[0].nodeValue;
attri = v[j].getAttribute("id");
myStr += "";
myStr += text;
myStr += " ";
}
}
myStr += " ";
}
myStr += "
";
$("#div1").html(myStr);
//document.getElementById("div1").innerHTML = myStr;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
clear();
}
//live方法实时监测html,耗用资源
$(".delet").live("click",function (e) {
var Like = $(e.target).parent().attr("id"); //通过e.target获取被点击的元素,与this不同
var idLike = Like.substring(0, 10); // 从索引0开始到8(不包括8)
var idLike0 = idLike + "0";
var x = document.getElementById(idLike0).innerText;
$.ajax({
url: "WebService.asmx/DoSome", //发送到本页面后台AjaxMethod方法
type: "POST",
dataType: "text/xml",
async: true, //async翻译为异步的,false表示同步,会等待执行完成,true为异步
//contentType: "application/json; charset=utf-8", //不可少
data: {
x: x
},
success: function (data) {
//将返回的xml信息转义
var str = data;
var reg = //g;
str = str.replace(reg, '>');
reg = /&/g;
str = str.replace(reg, '&');
reg = /'/g;
str = str.replace(reg, "'");
reg = /"/g;
str = str.replace(reg, '"');
var myStr = "销售表 ID 姓名 性别 生日 生产编号 数量 价格 编辑 删除 ";
var z = $(str).find("tr");
for (var i = 1; i < z.length; i++) {
myStr += "";
var v = $(z[i]).find("td");
for (var j = 0; j < v.length; j++) {
var text, attri, attribu;
if (j == 7 || j == 8) {
attri = v[j].getAttribute("id");
text = $(v[j]).find("span").text();
attribu = $(v[j]).find("span").attr("class");
myStr += "";
myStr += text;
myStr += " ";
} else {
text = v[j].childNodes[0].nodeValue;
attri = v[j].getAttribute("id");
myStr += "";
myStr += text;
myStr += " ";
}
}
myStr += " ";
}
myStr += "
";
document.getElementById("div1").innerHTML = myStr;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
});
$("#Button3").click(function () {
$("#Button5").attr('disabled', false);
clear();
});
function clear(){
document.getElementById("editId").value = "--自动生成--";
document.getElementById("TextBox2").value = "";
document.getElementById("RadioButton1").setAttribute("checked", false);
document.getElementById("RadioButton2").setAttribute("checked", false);
document.getElementById("TextBox4").value = "";
document.getElementById("TextBox5").value = "";
document.getElementById("TextBox6").value = "";
document.getElementById("TextBox7").value = "";
}