Understanding modelstate and HTML-assisted methods for MVC Learning

Source: Internet
Author: User
Understanding modelstate And verify html Auxiliary Methods The Controller class has a set of modelstate attributes, which can be used to indicate whether the model object passed to the view has an error. The error record in modelstate identifies the name and error information of model attributes, and allows you to specify friendly error information. When the updatemodel () auxiliary method assigns values to the attributes of the model object, if an exception or error occurs, the modelstate set is automatically written. For example, if the eventdate attribute type of the dinner object is datetime, when the updatemodel () method cannot assign the "entlib" string to eventdate, The updatemodel () method adds a record to the modelstate set, this indicates that an error occurs when the attribute is assigned a value. Developers can also explicitly write Code , Add the error records to the modelstate set, as shown in the following code. In the catch error handling exception block, we add it to the modelstate set according to the rule vilations (Rule conflict) Information in the dinner object. [Acceptverbs(Httpverbs. Post)] Public ActionresultEdit (IntID,FormcollectionFormvalues) { DinnerDinner = dinnerrepository. getdinner (ID ); Try { Updatemodel (dinner ); Dinnerrepository. Save (); ReturnRedirecttoaction ("Details",New{Id = dinner. dinnerid }); } Catch { Foreach(VaRIssueInDinner. getruleviolations ()) { Modelstate. addmodelerror (issue. propertyname, issue. errormessage ); } ReturnView (dinner ); } } Html Auxiliary methods and modelstate Integration HTML auxiliary methods, such as HTML. Textbox (), check the modelstate set when outputting the content. If an exception or error occurs in this attribute, the content entered by the user and the CSS error class are displayed. For example, in the edit view, we use the HTML. Textbox () helper method to present the eventdate attribute of the dinner object: <% = Html. Textbox ("Eventdate",String. Format ("{0: g }", Model. eventdate ))%> When a view is displayed in case of an error, the HTML. Textbox () method checks the modelstate set and whether an error is related to the eventdate attribute of the dinner object. When an error is found, the "entlib" Input submitted by the user is displayed as the parameter value, and the CSS error class is added to the <input type = "textbox"/> element, as shown below: <input class = "input-Validation-error" id = "eventdate" name = "eventdate" type = "text" value = "bogus"/> you can customize style. The default CSS error class-input-Validation-error is defined in the \ content \ site.css file. The style definition is as follows :. input-Validation-error {border: 1px solid # ff0000; Background-color: # ffeeee;} the CSS style displays the following text box for invalid input elements:
Html. validationmessage () Auxiliary Methods The HTML. validationmessage () auxiliary method is used to output modelstate error information related to a specific model attribute: <% = Html. validationmessage ("Eventdate")%> Output code: <SPAN class = "field-Validation-error"> the value 'entlib' is invalid </span> HTML. the validationmessage () auxiliary method also supports the second parameter, allowing developers to overwrite error messages: <% = Html. validationmessage ("Eventdate","*")%> Output code: <SPAN class = "field-Validation-error"> * </span> instead of the default error message. Html. validationsummary () Auxiliary Methods The HTML. validationsummary () auxiliary method displays the summarized error messages. All detailed error messages in the modelstate set are listed using the <ul> <li/> </ul> element:
The HTML. validationsummary () helper method receives an optional string parameter-defines a general error message and displays it before all detailed error messages: <% = Html. validationsummary ("Edit was unsuccessful. Please correct the errors and try again .")%> You can also define CSS to set the error message style. Use addruleviolations Auxiliary Methods The implementation method of the initial HTTP-POST edit uses a foreach loop statement to traverse the rule violations of the dinner object and add it to the modelstate set of the Controller: Catch { Foreach(VaRIssueInDinner. getruleviolations ()) { Modelstate. addmodelerror (issue. propertyname, issue. errormessage ); } ReturnView (dinner ); } To make the code more concise, we add the controllerhelpers class to the nerddinner project, implement the addruleviolations extension method, and add an auxiliary method for the ASP. net mvc modelstatedictionary class. This extension method encapsulates the logic of filling the modelstatedictionary collection class with the ruleviolation error information: Public Static Class Controllerhelpers { Public Static VoidAddruleviolations (ThisModelstatedictionary modelstate, Ienumerable<Ruleviolation> Errors) { Foreach(RuleviolationIssueInErrors) { Modelstate. addmodelerror (issue. propertyname, issue. errormessage ); } } } Next, we update the HTTP-POST Edit Method and use the above extension method to implement the dinner's rule violations to fill the modelstate set. Complete edit action Method implementation The following code implements all the logic of edit in the controller: // // Get:/dinners/edit/2 Public ActionresultEdit (IntID) { DinnerDinner = dinnerrepository. getdinner (ID ); ReturnView (dinner ); } // // Post:/dinners/edit/2 [Acceptverbs(Httpverbs. Post)] Public ActionresultEdit (IntID,FormcollectionFormvalues) { DinnerDinner = dinnerrepository. getdinner (ID ); Try { Updatemodel (dinner ); Dinnerrepository. Save (); ReturnRedirecttoaction ("Details",New{Id = dinner. dinnerid }); } Catch { Modelstate. addruleviolations (dinner. getruleviolations ()); ReturnView (dinner ); } } The advantages of the Edit Method are not only the Controller class, but also the view template does not need to care about the specific validation methods or business rules of the dinner model class. In the future, we can add additional business rules for the model class without requiring the controller and view to change the code. In this way, we can flexibly improve the application with minimal changes to the amount of code as needed. Program .

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.