第一种方案,最麻烦,而且容易出错(可能跟我个人不喜欢拼接字符串有关系);
第二种方案,有一定的通用性,但是不利于数据验证;
第三种方案,通用,可以进行有效的数据验证,应对一般的需求够用了,但是处理更复杂的对象不行;
第四种方案,几乎可以处理我们遇到的所有情况
另外,这是在asp教程.net mvc2中的使用,到了asp.net教程 mvc3,微软已经把jsonvalueproviderfactory作为内置的功能了
先来看看该功能的截图:
var test = "{ receiverid: 5, receivername: 'will', sex: 'f', createdate: '2011-02-21' }";
$.ajax({
url: "/home/test1",
type: "post",
cache: false,
data: test
});
streamreader reader = new streamreader(request.inputstream);
string bodytext = reader.readtoend();
网页特效serializer js = new javascriptserializer();
receiverinfo receiver = js.deserialize(bodytext);
//保存。。。
1 public class jsonbinder: imodelbinder
2 {
3 public object bindmodel(controllercontext controllercontext, modelbindingcontext bindingcontext)
4 {
5 streamreader reader = new streamreader(controllercontext.httpcontext.request.inputstream);
6 string json = reader.readtoend();
7
8 if (string.isnullorempty(json))
9 return json;
10
11 javascriptserializer serializer = new javascriptserializer();
12 object jsondata = serializer.deserializeobject(json);
13 return serializer.deserialize(json);
14 }
15 }
我们继承imodelbinder接口,实现其 方法:
public object bindmodel(controllercontext controllercontext, modelbindingcontext bindingcontext)
public actionresult test1([modelbinder(typeof(jsonbinder))] receiverinfo receiverinfo)
var b = {
receiverid: 5,
receivername: "will",
sex: "f",
createdate: "2011-02-21"
};
$.ajax({
url: "/home/test1",
type: "post",
cache: false,
data: b,
success: function(data) { alert(data.message); },
error: function(xhr, a, b) { alert(xhr.responsetext); }
});
public actionresult test1(receiverinfo receiverinfo)
[system.componentmodel.dataannotations.required(errormessage = "收货人必须填写")]
public string receivername { get; set; }
public class receiverinfochild
{
[system.componentmodel.dataannotations.required(errormessage = "childid必须填写")]
public string childid { get; set; }
}
并为类receiverinfo增加一个属性public list
protected void application_start()
{
arearegistration.registerallareas();
registerroutes(routetable.routes);
valueproviderfactories.factories.add(new jsonvalueproviderfactory());
}
var receiverinfo = [
{
receiverinfochild: [{ childid: "1" }, { childid: "11"}],
receiverid: 5,
receivername: "will",
sex: "f",
createdate: "2011-02-21"
},
{
receiverinfochild: [{ childid: "2" }, { childid: "22"}],
receiverid: 5,
receivername: "will",
sex: "f",
createdate: "2011-02-21"
}
];
$.ajax({
url: "/home/test1",
type: "post",
cache: false,
contenttype: "application/json;charset=utf-8",
data: json.stringify(receiverinfo),
success: function(data) { alert(data.message); },
error: function(xhr, a, b) { alert(xhr.responsetext); }
});
public actionresult test1(listreceiverinfo)
我的博物馆故事 官方安卓版v1.61.2
我的博物馆故事是一款以消除为主题的经营养成类手游,在这里玩家
专业模拟飞行10 手机版v12.2.4
专业模拟飞行10安卓版是一款飞行休闲手游,顶尖的物理飞行引擎
动物起义战斗模拟器二琳同款 最新版v4.1.1
动物起义战斗模拟器是一个非常有趣的模拟类游戏,玩家可以召唤各
迷你世界七周年 安卓手机版v1.43.0
迷你世界7周年是一款由《迷你世界》官方推出的庆祝特别版本,在
劫后公司无限资源版 v1.0.5.1
劫后公司内置菜单版是游戏的破解版本,在该版本中为玩家提供了内