Json Binding, Validate, and mvcjson in ASP. NET MVC

Source: Internet
Author: User

Json Binding, Validate, and mvcjson in ASP. NET MVC

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:

Var test = & quot; {ReceiverId: 5, ReceiverName: 'Will ', Sex: 'F', CreateDate: '2017-02-21'} & quot ;;

Then save it to the database using Jquery. The Code is as follows:


$. Ajax ({
Url: & quot;/Home/test1 & quot ;,
Type: & quot; post & quot ;,
Cache: false,
Data: test
});

Then you perform the following operations in the Action:

StreamReader reader = new StreamReader (Request. InputStream );
String bodyText = reader. ReadToEnd ();
JavaScriptSerializer js = new JavaScriptSerializer ();
ReceiverInfo javaser = js. DeserializeReceiverInfo & gt; (bodyText );
// Save...

2. Use custom ModelBinder


JsonBinder 

1Public class JsonBinderT & gt;: 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 & gt; (json );
14}
15}
 

We inherit the IModelBinder interface to implement its method:

Public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext)

You can. We can use the following in Action:


Public ActionResult Test1 ([ModelBinder (typeof (JsonBinderReceiverInfo & gt;)] 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: & quot; will & quot ;,
Sex: & quot; F & quot ;,
CreateDate: & quot; 2011-02-21 & quot;
};
$. Ajax ({
Url: & quot;/Home/test1 & quot ;,
Type: & quot; post & quot ;,
Cache: false,
Data: B,
Success: function (data) {alert (data. message );},
Error: function (xhr, a, B) {alert (xhr. responseText );}
});


Action Statement:


Public ActionResult Test1 (ReceiverInfo 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 = & quot; Required for the receiver & quot;)]
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 scheme (inheriting IValueProvider) in MVC is enough, so we only need to inherit ValueProviderFactory to implement its method: public override IValueProvider GetValueProvider (ControllerContext controllerContext) you can see JsonValueProviderFactory for the specific code.

We define another class:

ReceiverInfoChild

Public class ReceiverInfoChild
{
[System. ComponentModel. DataAnnotations. Required (ErrorMessage = & quot; ChildId Required & quot;)]
Public string ChildId {get; set ;}
}


Add a public List 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 (& quot; application/json & quot;, StringComparison. ordinalIgnoreCase) to determine whether the request is a json object. Therefore, when submitting data, we need to write:


Var ReceiverInfo = [
{
ReceiverInfoChild: [{ChildId: & quot; 1 & quot ;},{ ChildId: & quot; 11 & quot;}],
ReceiverId: 5,
ReceiverName: & quot; will & quot ;,
Sex: & quot; F & quot ;,
CreateDate: & quot; 2011-02-21 & quot;
},
{
ReceiverInfoChild: [{ChildId: & quot; 2 & quot ;}, {ChildId: & quot; 22 & quot;}],
ReceiverId: 5,
ReceiverName: & quot; will & quot ;,
Sex: & quot; F & quot ;,
CreateDate: & quot; 2011-02-21 & quot;
}
];
$. Ajax ({
Url: & quot;/Home/test1 & quot ;,
Type: & quot; post & quot ;,
Cache: false,
ContentType: & quot; application/json; charset = UTF-8 & quot ;,
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:


Public ActionResult Test1 (ListReceiverInfo & gt; 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.


How can I use the internal authentication function of ASPNET MVC3 to upload the same verification code to the front-end and back-end?

Last Updated: 11:36:48 on May 6, this article mainly describes how to use IClientValidatable. This interface allows developers to create front-end and back-end verification certificates, the native provides the Range, RegularExpression, Required, StringLength, Compare, and Remote verification rules that are frequently used in real life. This ASP. net mvc 3 has been changed to jQuery. validate is used as the front-end verification engine, and the unobtrusive design mode is used to integrate and extract data, making HTML still beautiful, with such a big change, you can understand ASP. net mvc 3 does not cover the shortcomings of the previous version. The following describes how to use the internal validation rules. Create an ASP. net mvc 3 is a native form board. After reading the line, go to the hosts plane of the member (set it to/Account/Register) if nothing is left blank, simply press "Register" to have the verification code, deliberately disable the Javascript of the browser, invalidate the front-end certificate, and then press "Register 」
Why is there a license?
This version is very good because it has already generated an AccountModels and added a certificate, open the repository and pull it to the backend to find the Class RegisterModel public class RegisterModel {[Required] [Display (Name = "User name")] public string UserName {get; set ;} [Required] [DataType (DataType. emailAddress)] [Display (Name = "Email address")] public string Email {get; set;} [Required] [StringLength (100, errorMessage = "The {0} must be at least {2} characters long. ", MinimumLengt H = 6)] [DataType (DataType. password)] [Display (Name = "Password")] public string Password {get; set;} [DataType (DataType. password)] [Display (Name = "Confirm password")] [Compare ("Password", ErrorMessage = "The password and confirmation password do not match. ")] public string ConfirmPassword {get; set ;}}the background color is the Attribute of the certificate, because this article mainly states that the credit card is irrelevant to the credit card, the Attribute is not introduced because of these settings, therefore, you must renew the certificate to support the front-end and back-end certificates. The effect shown above is the preset Required verification rules. It is a mandatory limitation, but since there are so many configurations supported, it's better to have a try. Public class RegisterModel {[Required] // Required [StringLength (3, Minimu ...... remaining full text>

How to parse json in aspnet mvc

Public static DataTable JsonToDataTable (string strJson)
{
// Retrieve the table name
Regex rg = new Regex (@"(? <= {) [^:] + (? =: \ [) ", RegexOptions. IgnoreCase );
String strName = rg. Match (strJson). Value;
DataTable tb = null;
// Remove the table name
StrJson = strJson. Substring (strJson. IndexOf ("[") + 1 );
StrJson = strJson. Substring (0, strJson. IndexOf ("]");

// Obtain data
Rg = new Regex (@"(? <= {) [^}] + (? = })");
MatchCollection mc = rg. Matches (strJson );
For (int I = 0; I <mc. Count; I ++)
{
String strRow = mc [I]. Value;
String [] strRows = strRow. Split (',');

// Create a table
If (tb = null)
{
Tb = new DataTable ();
Tb. TableName = strName;
Foreach (string str in strRows)
{
DataColumn dc = new DataColumn ();
String [] strCell = str. Split (':');
Dc. ColumnName = strCell [0]. ToString ();
Tb. Columns. Add (dc );
}
Tb. AcceptChanges ();
}

// Add content
DataRow dr = tb. NewRow ();
For (int r = 0; r <strRows. Length; r ++)
{
... The remaining full text>

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.