E-Commerce website Payment function page often has a lot of information, for this information is often a step-by-step to save, then use Ajax is the most appropriate, such as the consignee information module. The new and edited save for this information is done with Ajax. So there are several ways to do this, and I think of the following.
Let's take a look at the screenshot of this feature:
Typically this information corresponds to an entity class, which is named: Receiverinfo, for simplicity's sake, I define receiverinfo as follows:
1, the need to splice the value of the JSON text, and then action inside the processing
First you need to concatenate the values you want to save into a JSON text, similar to the following:
- var test = "{receiverid:5, Receivername:" Would ", Sex:" F ", CreateDate:" 2011-02-21 "};
Then use jquery to save it to the database with the following code:
- $.ajax ({
- URL: "/home/test1",
- Type: "Post",
- Cache:false,
- Data:test});
Then you do this in the action:
- StreamReader reader = new StreamReader (request.inputstream);
- String bodyText = reader. ReadToEnd ();
- JavaScriptSerializer js = new JavaScriptSerializer ();
- Receiverinfo receiver = js. Deserialize<receiverinfo> (BodyText);
- Save...
2, the use of customized Modelbinder implementation
Jsonbinder
- public class Jsonbinder<t>: Imodelbinder
- {
- public Object Bindmodel (ControllerContext controllercontext, Modelbindingcontext BindingContext)
- {
- StreamReader reader = new StreamReader (controllerContext.HttpContext.Request.InputStream);
- String json = reader. ReadToEnd ();
- if (string. IsNullOrEmpty (JSON))
- return JSON;
- JavaScriptSerializer serializer = new JavaScriptSerializer ();
- Object Jsondata = Serializer. Deserializeobject (JSON);
- Return serializer. Deserialize<t> (JSON);
- }
- }
We inherit the Imodelbinder interface and implement its methods:
- public Object Bindmodel (ControllerContext controllercontext, Modelbindingcontext BindingContext)
Can. We can use this in action:
- Public ActionResult Test1 ([Modelbinder (typeof (Jsonbinder<receiverinfo>))] Receiverinfo Receiverinfo)
So our custom Imodelbinder will replace Defaultmodelbinder to complete the data binding.
3. Pass a JSON object directly
The above two methods do not use the System.ComponentModel.DataAnnotations of MVC for effective data validation. You may need to validate yourself manually, which undoubtedly adds to the workload.
Let's try this way.
The writing of the front end
- var B = {
- Receiverid:5,
- Receivername: "Would",
- 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); }});
The action:
- Public ActionResult Test1 (Receiverinfo receiverinfo)
We can get the binding data normally. And we can also use System.ComponentModel.DataAnnotations for data validation. We make the following changes for Receiverinfo:
- [System.ComponentModel.DataAnnotations.Required
- (errormessage = "Consignee must fill in")] public string Receivername {get; set;}
And at the front end of the Receivername assignment is an empty string, executed again, get prompted:
Good, but we have new requirements, that is to pass more complex objects, such as Object nested objects, objects have collection properties, this way is not competent.
4, the use of Mvcfutures jsonvalueproviderfactory
Each version of MVC has a mvcfutures that has some extra functionality, some of which will be added to the next release, and these features can be useful at some point. I looked at the class inside and found that there was a class jsonvalueproviderfactory that was just a commit and a data validation process for complex objects. Because the JSON object requires a specific resolution to use the default Defaultmodelbinder, the parsing process needs to be completed in the valueprovider phase, so a specific valueprovider to Defaultmodelbinder is required. We need to implement a valueproviderfactory and Ivalueprovider, while the dictionaryvalueprovider<tvalue> inside MVC (inherited Ivalueprovider) is enough to use, so just inherit valueproviderfactory to implement its methods: public override Ivalueprovider Getvalueprovider ( ControllerContext ControllerContext) can be, the specific code you can see jsonvalueproviderfactory.
We define another class:
Receiverinfochild
- public class receiverinfochild{
- [System.ComponentModel.DataAnnotations.Required
- (errormessage = "childID must fill in")]
- public string childID {get; set;}}
and add an attribute to the class Receiverinfo public list<receiverinfochild> receiverinfochild {get; set;}
We put the jsonvalueproviderfactory out in the project, and then in the Global.asax register, you can use.
- protected void Application_Start () {
- Arearegistration.registerallareas ();
- RegisterRoutes (routetable.routes);
- VALUEPROVIDERFACTORIES.FACTORIES.ADD (New
- Jsonvalueproviderfactory ());}
Because the jsonvalueproviderfactory has: if (!controllercontext.httpcontext.request.contenttype.startswith) ("application/ JSON, StringComparison.OrdinalIgnoreCase) to determine if the incoming request is a JSON object, so when we submit the data we need to write this:
- var receiverinfo = [
- {
- Receiverinfochild: [{childid: "1"}, {childid: "11"}],
- Receiverid:5,
- Receivername: "Would",
- Sex: "F",
- CreateDate: "2011-02-21"
- },
- {
- Receiverinfochild: [{childid: "2"}, {childid: "22"}],
- Receiverid:5,
- Receivername: "Would",
- 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);}});
where Json.stringify (Receiverinfo) converts a JSON object into a string, where you can download the class library.
In the action, we can write this:
- Public ActionResult Test1 (list<receiverinfo> receiverinfo)
Look at the results of the debugging:
Values are bound completely properly. Let's look at data validation again:
So far, we've experimented with four different scenarios:
The first option, the most troublesome, and error prone (may be related to my personal dislike of stitching strings);
The second scheme has certain generality, but it is not good for data verification.
The third scheme, universal, can perform effective data validation and should be sufficient for general requirements, but not for more complex objects;
A fourth scenario that can handle almost every situation we encounter
In addition, this is the use of ASP.net MVC2, to the ASP.net MVC3, Microsoft has put jsonvalueproviderfactory as a built-in function.
Original link: http://www.cnblogs.com/WillMeng/archive/2011/03/01/json_binding_validate.html
"Edit Recommendation"