Hello everyone, please tell ModelState.IsValid why ModelState.IsValid does not see a validation error when assigning a knowingly incorrect model to the ViewData.Model property? Here is the class

 public class Class1 { [Required] public string EnterName { get; set; } [Required] public string EnterMessage { get; set; } } 

But the method of action

 public ActionResult Index(string EnterName, string EnterMessage) { ViewData.Model = new MvcApplication5.Models.Class1(); ViewBag.M = ModelState.IsValid; return View(); } 

As can be seen from the action code, I assign a class with empty properties, and this is not valid due to the [Required] attributes, however ViewBag.M = ModelState.IsValid; gives true. Why ??

    1 answer 1

    Because

    The ModelState object saves all the values ​​that the user entered for the properties of the model, as well as all the errors associated with each property and with the model as a whole. If there are any errors in the ModelState object, the ModelState.IsValid property will return false

    validation is performed for a user-entered model.

    What is the sacred meaning to check the internal data?

    • Thank. That is, only the result of the model data binding is stored in this object? What was entered in the form, then goes as an argument for the action method and then it is validated and the results of the validation are written in ModelState ? - Polyakov Sergey
    • one
      @polyakov_s, I do not remember exactly. And I do not remember whether it is possible to explicitly call validation. But it makes no sense to check my own data for validity. If the form zababmityat with such, it should work. And in general, it seems that the model usually appears in the View argument, and not so. - Qwertiy