JSON binding and validate in ASP. NET MVC

Source: Internet
Author: User

Introduction: The payment page of an e-commerce website usually contains a lot of information. The storage of such information is often completed step by step. Therefore, Ajax is the most suitable, for example, the receiver information module. Ajax is used to create and edit and save the information. There are several ways to complete this operation, I think of the following methods.

Let's take a look at this feature:

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:

 
VaRTest= "{Receiverid: 5, receivername: 'Will ', sex: 'F', createdate: '2017-02-21 '}";

Then save it to the database with jquery,CodeAs follows:

$. Ajax ({
URL:"/Home/test1",
Type:"Post",
Cache:False,
Data: Test
});

Then you perform the following operations in the action:

  streamreader  =    New   streamreader (request. inputstream); 
string bodytext = reader. readtoend ();
javascriptserializer 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 = 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 ObjectBindmodel (controllercontext, modelbindingcontext bindingcontext)

You can. We can use the following in action:

PublicActionresult test1 ([modelbinder (Typeof(Jsonbinder<Receiverinfo>)] Receiverinfo)

In this way, we customize 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:

PublicActionresult 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= "The recipient must enter")]
Public StringReceivername {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 ClassReceiverinfochild
{
[System. componentmodel. dataannotations. Required (errormessage= "Childid is required")]
Public StringChildid {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 VoidApplication_start ()
{
Arearegistration. registerallareas ();

Registerroutes (routetable. routes );

Valueproviderfactories. Factories. Add (NewJsonvalueproviderfactory ());
}

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: " APP/JSON; charset = UTF-8 " ,
Data: JSON. stringify (receiverinfo ),
Success: Function (Data) {alert (data. Message );},
Error: Function (Xhr, a, B) {alert (xhr. responsetext );}
});

JSON. stringify (receiverinfo) converts a JSON object to a string. You can download this class library here.

In the action, we can write it like this:

 
PublicActionresult 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:

So far, we have experimented with four solutions:

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. NET MVC2. in ASP. NET mvc3, Microsoft has made jsonvalueproviderfactory a built-in function.

Related Article

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.