保存DataGrid数据到数据库
By ZYZ
在使用JQuery EsayUI中有时会需要将DataGrid(数据表格)的数据保存到数据库中。下面我们来看看这是怎么做到的。
既然要保存数据,首先得获取数据,毕竟DataGrid没有Form有submit那样的函数可以直接提交给服务器。
首先,我们先在浏览器上得到数据,DataGrid有两种方法可供选择:
getData none 返回加载完毕后的数据。
getRows none 返回当前页的所有行。
通过getRows获得的数据就是DataGrid中所有行的数据
而通过getData方法得到的数据不但包括所有行数据,还包括total属性。
值得注意的是这两种方法得到的数据都是object型的。
var rowsData = $('#tbQuestion').datagrid('getRows');
这里我们采用一种构造json数据的方法来处理得到的object数据。
var json =JSON.stringify(rowsData);
有时候我们只需要其中的某几列数据而非全部数据。这时候就需要使用遍历了:
//构造json数据传送到服务器
var json = [];
var loc;
$.each(rowsData, function (i) {
loc= { "Category": rowsData[i].Category,
"Number": rowsData[i].Number,
"Score": rowsData[i].Score,
"KnowledgeCode":rowsData[i].Knowledge,
"Difficulty":rowsData[i].Difficulty,
"Questions":rowsData[i].Questions
};
json.push(loc);
});
json = JSON.stringify(json); //转换成json数据
经过这种方法处理后的数据是标准的json数据,属于字符串类型,可以直接通过post或者get传递给服务器。
服务器接收时选择使用context.Request.Params获取,如果使用context.Request[]获取的话会造成数据的丢失。
string josnArray= context.Request.Params["json"];
在服务器端,这里使用JavaScriptSerializer类来处理传递来的json数据。将其字符串型的json序列化成数组。当然,这里还需要有个容器,用来装入得到的数组。
//解码传来的json数据,解码成数组,用泛型接收
JavaScriptSerializerjsonSerializer = new JavaScriptSerializer();
ist<QuestionList>questionList = new List<QuestionList>();
questionList =(List<QuestionList>)jsonSerializer.Deserialize(josnArray,typeof(List<QuestionList>));
其中QuestionList定义为:
public partial class QuestionList
{
public string Category { get; set; }
public float Score { get; set; }
public string Questions { get; set; }
public int Number { get; set; }
public string KnowledgeCode { get; set; }
public string Difficulty { get; set; }
}
结果得到:
得到的泛型数据很方便使用,它支持多种灵活的调用方式。例如
for (int i = 0;i < questionList.Count; i++)
{
model.Category =questionList[i].Category;
model.Score =decimal.Parse(questionList[i].Score.ToString());
string[] questions =questionList[i].Questions.Split(',');//拆分试题ID组成数组
foreach (string question inquestions)
{
model.Question =int.Parse(question.ToString());
dal.Add(model);
count++;
}
}
剩下的,就是使用三层架构将数据按照需求保存到数据库了。
JavaScriptSerializer类的官方文档:
泛型的官方文档:
http://msdn.microsoft.com/zh-cn/library/512aeb7t(v=vs.90).aspx