第一种方案,最麻烦,而且容易出错(可能跟我个人不喜欢拼接字符串有关系);
第二种方案,有一定的通用性,但是不利于数据验证;
第三种方案,通用,可以进行有效的数据验证,应对一般的需求够用了,但是处理更复杂的对象不行;
第四种方案,几乎可以处理我们遇到的所有情况
另外,这是在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)