The first solution is the most troublesome and error-prone (it may be related to my personal dislike of concatenating strings );
The second scheme has a certain degree of universality, but is not conducive to data verification;
The third solution is generic and can be used for effective data verification. It is sufficient to deal with general requirements, but it cannot handle more complex objects;
The fourth solution can handle almost all the situations we encounter
In addition, this is used in asp tutorial. net mvc2. In asp.net tutorial mvc3, Microsoft has made jsonvalueproviderfactory a built-in function.
Let's take a look at the screenshot of this function:
Generally, this information corresponds to an object class and is named receiverinfo. For simplicity, I define receiverinfo as follows:
1. Splice the required values into json text and process them in the action column.
First, you need to splice the value to be saved into a json text, similar:
Var test = "{receiverid: 5, receivername: 'Will ', sex: 'F', createdate: '2017-02-21 '}";
Save it to the database using jquery. The code is as follows:
$. Ajax ({
Url: "/home/test1 ",
Type: "post ",
Cache: false,
Data: test
});
Then you perform the following operations in the action:
Streamreader reader = new streamreader (request. inputstream );
String bodytext = reader. readtoend ();
Webpage special effects serializer js = new javascriptserializer ();
Receiverinfo receiver = js. deserialize <receiverinfo> (bodytext );
// Save...
2. Use custom modelbinder
Jsonbinder
1
Public class jsonbinder <t>: imodelbinder
2 {
3 public object bindmodel (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 <t> (json );
14}
15}
We inherit the imodelbinder interface to implement its Method:
Public object bindmodel (controllercontext, modelbindingcontext bindingcontext)
You can. We can use the following in action:
Public actionresult test1 ([modelbinder (typeof (jsonbinder <receiverinfo>)] receiverinfo)
In this way, the custom imodelbinder replaces defamodelmodelbinder to complete data binding.
3. Directly pass a json object
The above two methods do not use mvc's system. componentmodel. dataannotations for effective data verification. You may need to manually verify it, which will undoubtedly increase the workload.
Let's try this method.
Frontend statement:
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 );}
});
Action statement:
Public actionresult test1 (receiverinfo)
We can normally get the bound data. We can also use system. componentmodel. dataannotations for data verification. Make the following changes for receiverinfo:
[System. componentmodel. dataannotations. required (errormessage = "required by the receiver")]
Public string receivername {get; set ;}
And assign a blank string to receivername at the front end. Execute the code again. The following message is displayed:
Good, but we have new requirements, that is, to pass more complex objects, such as object nesting objects and objects with set attributes, this method is not competent.
4. Use jsonvalueproviderfactory of mvcfutures
Each version of mvc has an mvcfutures, which has some additional features, some of which will be added to the next version, and these features are useful in some cases. I checked the classes and found that a class jsonvalueproviderfactory is used to process the submission and data verification of complex objects. The default defamodelmodelbinder can be used for json objects only after specific parsing, and this parsing process needs to be completed in the valueprovider stage. Therefore, a specific valueprovider must be implemented to defamodelmodelbinder. We need to implement a valueproviderfactory and ivalueprovider, while the dictionaryvalueprovider in mvc <tvalue> (inheriting ivalueprovider) is enough, so we only need to inherit the valueproviderfactory implementation method: public override ivalueprovider getvalueprovider (controllercontext). For specific code, see jsonvalueproviderfactory.
We define another class:
Receiverinfochild
Public class receiverinfochild
{
[System. componentmodel. dataannotations. required (errormessage = "childid required")]
Public string childid {get; set ;}
}
Add a public list <receiverinfochild> receiverinfochild {get; set;} to the class receiverinfo ;}
We put jsonvalueproviderfactory out in the project, and then register it in global. asax to use it.
Protected void application_start ()
{
Arearegistration. registerallareas ();
Registerroutes (routetable. routes );
Valueproviderfactories. factories. add (new jsonvalueproviderfactory ());
}
Because jsonvalueproviderfactory contains: if (! Controllercontext. httpcontext. request. contenttype. startswith ("application/json", stringcomparison. ordinalignorecase) to determine whether the request is a json object. Therefore, we need to write the following when submitting data:
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 );}
});
Here, json. stringify (receiverinfo) is used to convert a json object into a string. You can download this class library from the following link to the pstutorial: // github.com/douglascrockford/json-js ">.
In the action, we can write it like this:
Public actionresult test1 (list <receiverinfo> receiverinfo)
Let's take a look at the debugging results:
The value is fully bound. Let's take a look at data verification: