Use the UpdataModel method in ASP. NET MVC

Source: Internet
Author: User

In ASP. net mvc Beta, an overload with the IValueProvider parameter is provided in the UpdataModel method. So what is the use of this IValueProvider?

Let's take a look at a simple scenario. For example, our blog system has a Post object, which has a Tags attribute and Categories attribute. Their types are:

 
 
  1. Post. Tags: StateList<String>(A List in BlogEngine. NET<T>Extension type)
  2. Post. Categories: StateList<Category> 


If we want to use the UpdataModel method in ASP. net mvc to update the Form data we Post to our Post object, there may be the following code:

 
 
  1. ///<Summary> 
  2. /// Save the submitted content of the new essay form to the database
  3. ///</Summary> 
  4. [AcceptVerbs ("POST"), ActionName ("NewPost")]
  5. Public ActionResult SaveNewPost (FormCollection form)
  6. {
  7. PostPost=NewPost ();
  8. Try
  9. {
  10. UpdateModel (post, new [] {"Title", "Content", "Slug", "Tags", "Categories "});
  11. }
  12. Catch
  13. {
  14. Return View (post );
  15. }
  16. ..
  17. }

Obviously, in the above Code, when we use UpdateModel to update the Tags and Categories attributes, it is impossible to succeed, the UpdateModel method does not know how to convert the "Tags" and "Categories" data submitted by Form to the StateList <string> type and StateList <Category> type. At this time, we need to provide a ValueProvider for this conversion.

To implement a ValueProvider, we only need to implement the GetValue method of the IValueProvider interface and return the result of a ValueProviderResult. Next we will write a PostValueProvider to implement the above situation. The Code is as follows:

 
 
  1. PostValueProvider
  2. PublicclassPostValueProvider: IValueProvider
  3. {
  4. PrivateControllerContextcontext;
  5. // Privatedefavaluvalueproviderdprovider;
  6.  
  7. PublicPostValueProvider (ControllerContextcontext)
  8. {
  9. This. context= Context;
  10. //DProvider=Newdefavaluvalueprovider(Context );
  11. }
  12.  
  13. # RegionIValueProvider Member
  14.  
  15. PublicValueProviderResultGetValue (stringname)
  16. {
  17. If (string. IsNullOrEmpty (name ))
  18. {
  19. ThrownewArgumentException ("parameter cannot be blank", "name ");
  20. }
  21. Switch (name)
  22. {
  23. Case "Tags ":
  24. ReturnGetTagsValue ();
  25. Case "Categories ":
  26. ReturnGetCategoriesValue ();
  27. Default:
  28. Returnnewdefavaluvalueprovider (context). GetValue (name );
  29. }
  30. }
  31.  
  32. # Endregion
  33.  
  34. PrivateValueProviderResultGetTagsValue ()
  35. {
  36. StringstrTags=GetValueFromRequest("Tags ");
  37. If (string. IsNullOrEmpty (strTags ))
  38. {
  39. Returnnull;
  40. }
  41.  
  42. String []Tags=StrTags. Split (newstring [] {","}, StringSplitOptions.
    RemoveEmptyEntries );
  43. StateList<String>TagsList=NewStateList<String>();
  44. Foreach (stringtagintags)
  45. {
  46. TagsList. Add (tag. Trim (). ToLowerInvariant ());
  47. }
  48.  
  49. ReturnnewValueProviderResult (tagsList, strTags, CultureInfo.
    InvariantCulture );
  50. }
  51.  
  52. PrivateValueProviderResultGetCategoriesValue ()
  53. {
  54. StringstrCategories=GetValueFromRequest("Categories ");
  55. If (string. IsNullOrEmpty (strCategories ))
  56. {
  57. Returnnull;
  58. }
  59.  
  60. String []Categories=StrCategories. Split (newstring [] {","},
    StringSplitOptions. RemoveEmptyEntries );
  61. StateList<Category>List=NewStateList<Category>();
  62. Foreach (stringcincategories)
  63. {
  64. List. Add (Category. GetCategory (newGuid (c )));
  65. }
  66.  
  67. ReturnnewValueProviderResult (list, strCategories, CultureInfo. InvariantCulture );
  68. }
  69.  
  70. PrivatestringGetValueFromRequest (stringname)
  71. {
  72. Stringvalue=Null;
  73. HttpRequestBaserequest=Context. HttpContext. Request;
  74. If (request! = Null)
  75. {
  76. If (request. QueryString! = Null)
  77. {
  78. Value=Request. QueryString [name];
  79. }
  80. If (string. IsNullOrEmpty (value) & (request. Form! = Null ))
  81. {
  82. Value=Request. Form [name];
  83. }
  84. }
  85.  
  86. Returnvalue;
  87. }
  88. }

Then we can use our PostValueProvider in the UpdateModel method:

 
 
  1. ///<Summary> 
  2. /// Save the submitted content of the new essay form to the database
  3. ///</Summary> 
  4. [AcceptVerbs ("POST"), ActionName ("NewPost")]
  5. PublicActionResultSaveNewPost (FormCollectionform)
  6. {
  7. Postpost=NewPost();
  8. Try
  9. {
  10. UpdateModel (post, new [] {"Title", "Content", "Slug", "Tags", "Categories "},
    NewPostValueProvider (ControllerContext ));
  11. }
  12. Catch
  13. {
  14. ReturnView (post );
  15. }
  16.  
  17. ..
  18. }


The above describes how to use the UpdataModel method in ASP. net mvc.

  1. Introduction to ASP. NET 2.0 Virtual Hosts
  2. Introduction to ASP. NET Applications
  3. Optimize ASP. NET 2.0 Profile Provider
  4. ASP. NET pipeline Optimization
  5. Introduction to ASP. NET Routing Engine

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.