JSON binding and validate in ASP.

Source: Internet
Author: User
Tags httpcontext

Introduction: E-commerce site payment function page will often have a lot of information, for the preservation of these information is often done in step, then use Ajax is the most suitable, such as the consignee information module. The new and edited saves of this information are done using AJAX. So there are several ways to do this, and I think of the following.
Let's take a look at this feature:


In general, this information will correspond to an entity class, named: Receiverinfo, for simplicity, I define receiverinfo as follows:



1, the required values are stitched into JSON text, then action inside processing

First you need to stitch 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 the database with the following code:


$.ajax ({
URL: "/home/test1" 
    type: "post", 
    cache:false, 
    data:test 
});  

Then you do this in action:  

StreamReader reader = new StreamReader (request.inputstream); String bodyText = reader. ReadToEnd ();  
JavaScriptSerializer js = new JavaScriptSerializer ();  
receiverinfo receiver = js. Deserializereceiverinfo> (BodyText);  
//save ...  

2, using a custom Modelbinder implementation


Jsonbinder

1public class Jsonbindert> : 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. Deserializet> (JSON);  
14    } &NBSP


We inherit the Imodelbinder interface and implement its method:

public Object Bindmodel (ControllerContext controllercontext, Modelbindingcontext BindingContext)

Can. We can use this in action:


Public ActionResult Test1 ([Modelbinder (typeof (Jsonbinderreceiverinfo>))] Receiverinfo receiverinfo)

This way our custom imodelbinder will replace Defaultmodelbinder to complete the data binding.

3. Pass a JSON object directly

The above two methods do not use MVC's System.ComponentModel.DataAnnotations for effective data validation. You may need to manually verify yourself, adding to the workload.

Let's try this way.

The wording of the front end:

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);}
});


The action's wording:


Public ActionResult Test1 (receiverinfo receiverinfo)

We can normally get the data after the binding. 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 for receivername assignment to an empty string, execute again, get prompt:


Very good, but we have new requirements, that is to pass more complex objects, such as Object nested objects, objects have set properties, this method is not competent.


4, the use of Mvcfutures jsonvalueproviderfactory


Each version of MVC has a mvcfutures that has some extra features, some of which are added to the next version, and these features are useful at some point. I looked at the classes inside and found that there was a class jsonvalueproviderfactory that dealt with the submission of complex objects and data validation. Because a JSON object requires a specific resolution to use the default Defaultmodelbinder, this parsing process needs to be done in the valueprovider phase, so a specific valueprovider is required to be implemented for Defaultmodelbinder. We need to implement a valueproviderfactory and Ivalueprovider, and the Dictionaryvalueprovider in MVC (inherited Ivalueprovider) is enough to use, So just inherit valueproviderfactory to implement its method: public override Ivalueprovider Getvalueprovider (controllercontext ControllerContext), 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 a property to the class Receiverinfo public List receiverinfochild {get; set;}
We take jsonvalueproviderfactory out of the project, and then register it in the Global.asax, you can use it.


protected void Application_Start ()
{
Arearegistration.registerallareas ();

RegisterRoutes (routetable.routes);

VALUEPROVIDERFACTORIES.FACTORIES.ADD (New Jsonvalueproviderfactory ());
}


Because Jsonvalueproviderfactory has: if (!controllercontext.httpcontext.request.contenttype.startswith " Application/json&quot, StringComparison.OrdinalIgnoreCase)) to determine if the incoming request is a JSON object, so we need to write this when we submit the 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);}
});


where Json.stringify (Receiverinfo) converts a JSON object into a string, you can download the class library here.

In action, we can write this:


Public ActionResult Test1 (listreceiverinfo> receiverinfo)

Check the results of the debugs:



The value is completely bound to normal. Let's look at the data validation:



At this point, we have experimented with four different scenarios:

The first scenario, the most troublesome, and error prone (may be related to my personal dislike of splicing strings);

The second scheme has certain generality, but it is not good for data verification.

The third scenario, universal, can be effective data validation, to deal with the general needs of sufficient, but to deal with more complex objects do not;

A fourth scenario that can handle almost every situation we encounter

In addition, this is used in the ASP. NET MVC2, and Microsoft has put jsonvalueproviderfactory as a built-in feature to the ASP.

JSON binding and validate in ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.