How to use asp.net mvc to save user information for e-commerce website

Source: Internet
Author: User
Tags add define object end httpcontext implement net string

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:

 
  
  
  1. 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:

 
  
  
  1. $.ajax ({
  2. URL: "/home/test1",
  3. Type: "Post",
  4. Cache:false,
  5. Data:test});

Then you do this in the action:

 
  
  
  1. StreamReader reader = new StreamReader (request.inputstream);
  2. String bodyText = reader. ReadToEnd ();
  3. JavaScriptSerializer js = new JavaScriptSerializer ();
  4. Receiverinfo receiver = js. Deserialize<receiverinfo> (BodyText);
  5. Save...

2, the use of customized Modelbinder implementation

Jsonbinder

 
 
  1. public class Jsonbinder<t>: 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. if (string. IsNullOrEmpty (JSON))
  8. return JSON;
  9. JavaScriptSerializer serializer = new JavaScriptSerializer ();
  10. Object Jsondata = Serializer. Deserializeobject (JSON);
  11. Return serializer. Deserialize<t> (JSON);
  12. }
  13. }

We inherit the Imodelbinder interface and implement its methods:

 
  
  
  1. public Object Bindmodel (ControllerContext controllercontext, Modelbindingcontext BindingContext)

Can. We can use this in action:

 
  
  
  1. 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

 
  
  
  1. var B = {
  2. Receiverid:5,
  3. Receivername: "Would",
  4. Sex: "F",
  5. CreateDate: "2011-02-21"};$.ajax ({
  6. URL: "/home/test1",
  7. Type: "Post",
  8. Cache:false,
  9. DATA:B,
  10. Success:function (data) {alert (data.message);},
  11. Error:function (XHR, A, b) {alert
  12. (Xhr.responsetext); }});

The action:

 
  
  
  1. 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:

 
  
  
  1. [System.ComponentModel.DataAnnotations.Required
  2. (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

 
  
  
  1. public class receiverinfochild{
  2. [System.ComponentModel.DataAnnotations.Required
  3. (errormessage = "childID must fill in")]
  4. 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.

 
  
  
  1. protected void Application_Start () {
  2. Arearegistration.registerallareas ();
  3. RegisterRoutes (routetable.routes);
  4. VALUEPROVIDERFACTORIES.FACTORIES.ADD (New
  5. 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:

 
 
  1. var receiverinfo = [
  2. {
  3. Receiverinfochild: [{childid: "1"}, {childid: "11"}],
  4. Receiverid:5,
  5. Receivername: "Would",
  6. Sex: "F",
  7. CreateDate: "2011-02-21"
  8. },
  9. {
  10. Receiverinfochild: [{childid: "2"}, {childid: "22"}],
  11. Receiverid:5,
  12. Receivername: "Would",
  13. Sex: "F",
  14. CreateDate: "2011-02-21"}
  15. ];$.ajax ({
  16. URL: "/home/test1",
  17. Type: "Post",
  18. Cache:false,
  19. ContentType: "Application/json;charset=utf-8",
  20. Data:JSON.stringify (Receiverinfo),
  21. Success:function (data) {alert (data.message);},
  22. 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:

 
  
  
  1. 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"



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.