c# - ModelState not validating nested models after editing in controller -


i have nested viewmodels these two:

public class firstviewmodel {     public secondviewmodel secondviewmodel { get; set; } }  public class secondviewmodel {     [range(1, 12)]     public int month { get; set; } } 

if put month = 13; , call modelstate.isvalid (in controller) validation true.

edit:

this controller:

public actionresult create() {     return partialview(new firstviewmodel);     }  public httpstatuscoderesult create (firstviewmodel viewmodel){      viewmodel.secondviewmodel = new secondviewmodel();     viewmodel.secondviewmodel.month = 13;      if (modelstate.isvalid)     {         return new httpstatuscoderesult(200);     }     else     {         return new httpstatuscoderesult(304);     } } 

i'm making abstraction of problem, aren't real variables.

your question states "call modelstate.validate" in controller. there no such method, assume mean if (modelstate.isvalid).

the first step in model binding process parameters of method initialized, in case new instance of firstviewmodel. values of model set based on form data, route values, query string values etc. , validation errors associated properties of model added modelstate.

subsequently modifying value of properties in model has no affect on modelstate, if initial value of month valid, modelstate.isvalid return true irrespective of setting viewmodel.secondviewmodel.month = 13;

if want re-validate model, need use tryupdatemodel returns bool indicating if update succeeded

public httpstatuscoderesult create (firstviewmodel viewmodel) {   viewmodel.secondviewmodel = new secondviewmodel();   viewmodel.secondviewmodel.month = 13;   if (tryupdatemodel(viewmodel)   {     return new httpstatuscoderesult(200);   }   else   {     return new httpstatuscoderesult(304);   } } 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -