The use of modelstate in MVC

Source: Internet
Author: User

The Modelstate class in MVC needs to refer to the SYSTEM.WEB.MVC namespace in System.Web.Mvc.dll.

Property

Errors

Returns a Modelerrorcollection object that contains any errors that occurred during model binding.

Value

Returns a Valueproviderresult object that encapsulates the values that are bound during model binding.

Html helper methods and Modelstate integration

an HTML helper method, such as Html.textbox (), checks the Modelstate collection when the content is output. If the attribute is found to have an exception or an error, the user input content and CSS error classes are rendered.  For example, in the edit view, we use the Html.textbox () helper method to render the Eventdate property of the Dinner object:<%= html.textbox ("Eventdate", String.Format ("{0:g}", model.eventdate)) %>  When the view is rendered in the wrong way, the Html.textbox () method examines the Modelstate collection and checks to see if there is an error associated with the Eventdate property of the Dinner object. When errors are found, the user-submitted "EntLib" input is displayed as the parameter value, and the CSS error class is added to the <input type= "textbox"/> Element as follows:<input class= "Input-validation-error" id= "eventdate " name= "Eventdate"type= "text" value= "BOGUS"/>You can customize the style of the CSS error class. The default CSS error class –input-validation-error is defined in the \content\site.css file, and the style is defined as follows:. Input-validation-error{border:1px solid #ff0000;}   Html.validationmessage () auxiliary methodthe Html.validationmessage () helper method is used to output the Modelstate error message related to a specific model property: <%= html.validationmessage ("Eventdate") %>  The above code output:<span class= "Field-validation-error" > The value ' EntLib ' is invalid</span> the Html.validationmessage () helper method also supports the second parameter, which allows the developer to overwrite the error message:<%= html.validationmessage ("Eventdate", "*") %> The above code output: <span class= "Field-validation-error" > *</span>, instead of the default error message.   Html.validationsummary () auxiliary methodThe html.validationsummary () helper method renders a summary of the error messages, listing all the detailed error messages in the Modelstate collection through the <ul><li/></ul> elementThe html.validationsummary () helper method receives an optional string parameter – defines a generalized error message and is displayed in front of all detailed error messages:<%= html.validationsummary ("Edit was unsuccessful. Please correct the errors and try again. ") %> You can also define the style of the CSS settings error message.   using the Addruleviolations helper methodThe implementation of the initial http-post edit uses a foreach Loop statement that traverses the dinner object's rule violations and adds it to the controller's Modelstate collection:Catch{foreach (var issue in dinner. Getruleviolations ()){Modelstate.addmodelerror (issue. PropertyName, issue. errormessage);}return View (dinner);}  to make the code a little more concise, we added the Controllerhelpers class to the Nerddinner project and implemented the Addruleviolations extension method, adding a pair of ASP. Auxiliary methods for the Modelstatedictionary class. The extension method encapsulates the logic of populating the Modelstatedictionary collection class with ruleviolation error information:Public static Class Controllerhelpers{Public static void Addruleviolations (this modelstatedictionary modelstate,ienumerable<ruleviolation> Errors){foreach (ruleviolation issue in errors){Modelstate.addmodelerror (issue. PropertyName, issue. errormessage);}}} Next, we update the Http-post edit method, using the extension method described above to implement the dinner rule violations populate the Modelstate collection.   complete the implementation of the edit action methodThe following code implements all the logic of edit in the controller: C # code replication
////GET:/DINNERS/EDIT/2PublicActionResult Edit (IntId{Dinner Dinner=Dinnerrepository.getdinner (ID);ReturnView (dinner);} //// POST:/dinners/edit/2   [Acceptverbs (httpverbs.post)]  public  actionresult Edit (  int  ID, formcollection formvalues)   {Dinner Dinner  =  Dinnerrepository.getdinner (ID);  try    {Updatemodel (dinner);d innerrepository.save ();  Return  redirecttoaction ( " Details " ,  new    {id  =  dinner. Dinnerid} );}   catch    {modelstate.addruleviolations (dinner. Getruleviolations ());  return  View (dinner);} }                 /span>                
 The benefit of the implementation of the Edit method is not only the Controller class, but also the View view template does not have to care about the specific validation methods or business rules of the dinner model class. Later, we can add additional business rules to the model class without requiring the controller and view to change the code. In this way, we can flexibly improve the application based on the requirements, with minimal change in the amount of code.

The use of modelstate in MVC

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.