Use of modelstate in mvc and use of mvcmodelstate
In MVC, The ModelState class must reference the System. Web. Mvc namespace in System. Web. Mvc. dll.
Attribute
Errors
Returns a ModelErrorCollection object that contains any errors that occur during model binding.
Value
Returns a ValueProviderResult object that encapsulates the value bound during model binding.
Integrate Html auxiliary methods with ModelState
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 Html. the TextBox () auxiliary method presents the EventDate attribute of the Dinner object: <% = Html. textBox ("EventDate", String. format ("{0: g}", Model. eventDate) %> Html. the TextBox () method checks the ModelState set and whether an error is associated with 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 ;}
Html. ValidationMessage () Auxiliary MethodHtml. the ValidationMessage () auxiliary method is used to output ModelState error messages related to specific Model attributes: <% = Html. validationMessage ("EventDate") %> code output: <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 MethodHtml. the ValidationSummary () auxiliary method displays the summarized error messages. The <ul> <li/> </ul> element lists all the detailed error messages in the ModelState set in Html. the ValidationSummary () auxiliary 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 the CSS setting error message style.
AddRuleViolationsThe 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 (var issue in dinner. getRuleViolations () {ModelState. addModelError (issue. propertyName, issue. errorMessage);} return View (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 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 and use the extension method above to populate the ModelState set with Dinner's Rule Violations.
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/2public ActionResult Edit(int id){Dinner dinner = dinnerRepository.GetDinner(id);return View(dinner);} //// POST: /Dinners/Edit/2[AcceptVerbs(HttpVerbs.Post)]public ActionResult Edit(int id, FormCollection formValues) {Dinner dinner = dinnerRepository.GetDinner(id); try{UpdateModel(dinner);dinnerRepository.Save();return RedirectToAction("Details", new { id = dinner.DinnerID });}catch{ModelState.AddRuleViolations(dinner.GetRuleViolations());return View(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 applications with minimal changes to the amount of code as needed.
ModelStateAddModelError
ModelState is a dictionary type. The purpose of this sentence is to add an error message to ModelState. The first parameter is the Key, and the second parameter is the Value. The added error message is used in the VIEW corresponding to the CONTROLLER. <% = Html. validationMessage (key) %> or Html. validationSummary () is displayed -_-!!)
"Enter the password". You can replace it with any string you want to display.
Why is ModelStateIsValid always true in my MVC verification?
MVC is designed to solve a series of problems caused by WebForm controls, such as the huge ViewState, which is unacceptable for non-enterprise websites.
As for the problem of OO, MVC will only be more in line with the OO theory.