How to use ASP. net mvc to save user information of e-commerce websites

Source: Internet
Author: User

The payment function page of an e-commerce website usually contains a lot of information. The storage of such information is often completed step by step, so 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:

 
 
  1. var test = "{ ReceiverId: 5, ReceiverName: 'will', Sex: 'F', CreateDate: '2011-02-21' }"; 

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

 
 
  1. $.ajax({    
  2. url: "/Home/test1",    
  3. type: "post",    
  4. cache: false,    
  5. data: test}); 

Then you perform the following operations 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. Use custom ModelBinder

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 to implement its method:

 
 
  1. public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 

You can. We can use the following in Action:

 
 
  1. public ActionResult Test1([ModelBinder(typeof(JsonBinder<ReceiverInfo>))] 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 writing

 
 
  1. var b = {      
  2. ReceiverId: 5,      
  3. ReceiverName: "will",      
  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); }}); 

Action Statement:

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

 
 
  1. [System. ComponentModel. DataAnnotations. Required
  2. (ErrorMessage = "")] 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 DictionaryValueProvider in MVC <TValue> inherits IValueProvider) is enough, so we only need to inherit ValueProviderFactory to implement its method: public override IValueProvider GetValueProvider (ControllerContext controllerContext). For specific code, see JsonValueProviderFactory.

We define another class:

ReceiverInfoChild

 
 
  1. Public class ReceiverInfoChild {
  2. [System. ComponentModel. DataAnnotations. Required
  3. (ErrorMessage = "ChildId required")]
  4. Public string ChildId {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.

 
 
  1. protected void Application_Start(){      
  2. AreaRegistration.RegisterAllAreas();      
  3. RegisterRoutes(RouteTable.Routes);      
  4. ValueProviderFactories.Factories.Add(new   
  5. JsonValueProviderFactory());} 

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:

 
 
  1. var ReceiverInfo = [              
  2. {                  
  3. ReceiverInfoChild: [{ ChildId: "1" }, { ChildId: "11"}],                  
  4. ReceiverId: 5,                
  5. ReceiverName: "will",                
  6. Sex: "F",                  
  7. CreateDate: "2011-02-21"            
  8.   },              
  9. {                 
  10.  ReceiverInfoChild: [{ ChildId: "2" }, { ChildId: "22"}],                  
  11. ReceiverId: 5,                
  12. ReceiverName: "will",                
  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); }}); 

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:

 
 
  1. public ActionResult 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, which 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.

Edit recommendations]

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.