ASP.NET MVC 2 Model Validation (DataAnnotes) in a Subobject

Does the ASP.NET MVC 2 model validate subobjects?

I have a Filter instance from this class:

public class Filter
{
    [StringLength(5)]
    String Text { get; set; }
}

in my main object:

public class MainObject
{
    public Filter filter;
}

However, when I do TryValidateModel (mainObject), the check still works, even if the "Text" in MainObject.Filter.Text is longer than 5 characters.

Is this the goal, or am I doing something wrong?

+3
source share
1 answer

Two points:

  • Use public properties, not fields on models.
  • The instance you are trying to validate must go through the model binding in order for this to work

, :

public class Filter
{
    [StringLength(5)]
    public String Text { get; set; }
}

public class MainObject
{
    public Filter Filter { get; set; }
}

, , :

public ActionResult Index()
{
    // Here the instantiation of the model didn't go through the model binder
    MainObject mo = GoFetchMainObjectSomewhere();
    bool isValid = TryValidateModel(mo); // This will always be true
    return View();
}

, :

public ActionResult Index(MainObject mo)
{
    bool isValid = TryValidateModel(mo);
    return View();
}

, :

public ActionResult Index(MainObject mo)
{
    bool isValid = ModelState.IsValid;
    return View();
}

: TryValidateModel.

+1

Source: https://habr.com/ru/post/1753988/


All Articles