在我們開發web項目的時候,很多情況下需要從頁面傳遞一組數據獲取從後臺取一組數據。以前開發項目的時候會習慣性地選擇憑藉字符串:
在頁面中:
data=”data1:”+value1+”data2:”+value2;
然後後臺頁面通過String的Split方法拆分來得到對應字段的值。或者後臺拼接字符串,前臺拆分。
這樣確實能達到想要的結果。但會出現一些問題:當字段過多,很容易拼接出現問題。同時,當含有特殊字符時,轉化會出現一些問題。
通過Newtonsoft.Json.dll 中的序列化與反序列化來解決是一個不錯的辦法。
封裝序列化函數:
public class JsonHelper
{
public static string SerializeObject(Object value)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(value);
}
public static T DeserializeObject<T>(string json)
{
if (string.IsNullOrEmpty(json))
return default(T);
return JsonConvert.DeserializeObject<T>(json);
}
}
創建模型:
public class TableModel
{
public string Colom1 { get; set; }
public string Colom2 { get; set; }
public string Colom3 { get; set; }
public string Colom4 { get; set; }
}
然後就可以使用了:
1.前臺向後臺傳遞,通過Jquery的Json序列化:
var table = [];
table.push({ "Colom1": "11", "Colom2": "22", "Colom3": "33", "Colom4": "44" });
table.push({ "Colom1": "11", "Colom2": "22", "Colom3": "33", "Colom4": "44" });
table.push({ "Colom1": "11", "Colom2": "22", "Colom3": "33", "Colom4": "44" });
table.push({ "Colom1": "11", "Colom2": "22", "Colom3": "33", "Colom4": "44" });
table.push({ "Colom1": "11", "Colom2": "22", "Colom3": "33", "Colom4": "44" });
var data = { "data": JSON.stringify(table) };
//alert(jsonStr);
$.ajax({
type: 'post',
url: "/test/default/settable",
dataType: 'json',
data: data,
success: function (data) {
}
});
});
後臺接收:
[Route("settable")]
public ActionResult GetTable(string data)
{
List<TableModel> list = JsonHelper.DeserializeObject<List<TableModel>>(data);
return View();
}
2.通過後臺取值
[Route(“gettable”)]
public JsonResult GetTable()
{
List list = new List();
list.Add(new TableModel
{
Colom1 = “1”,
Colom2 = “2”,
Colom3 = “3”,
Colom4 = “4”
});
list.Add(new TableModel
{
Colom1 = “1”,
Colom2 = “2”,
Colom3 = “3”,
Colom4 = “4”
});
list.Add(new TableModel
{
Colom1 = “1”,
Colom2 = “2”,
Colom3 = “3”,
Colom4 = “4”
});
list.Add(new TableModel
{
Colom1 = “1”,
Colom2 = “2”,
Colom3 = “3”,
Colom4 = “4”
});
string result = JsonHelper.SerializeObject(list );
return Json(new {table= JsonHelper.SerializeObject(list )});
}
前臺反序列化:
$.ajax({
type: 'get',
url: "/test/default/gettable",
dataType: 'json',
success: function (data) {
var message = "";
data.table = JSON.parse(data.table); //發序列化
$.each(data.table, function (i, item) {
});
}
});
大致方式就是這樣。就不用再通過字符串的方式拼接json格式的對象了。