c# - Nested view model doesn't validate from unit tests in .net with DataAnnotations -


i have apicontroller, in have post method accepts variabletemplateviewmodel, looks this:

public class variabletemplateviewmodel {     public variabletemplateviewmodel() { }      public double version { get; set; }      [required]     public list<variableviewmodel> variables { get; set; } }  public class variableviewmodel {     public variableviewmodel() { }      [required(allowemptystrings=false, errormessage="variable name cannot empty")]     public string name { get; set; } } 

inside post method, validation check, so:

public void post(long id, [frombody]variabletemplateviewmodel model) {     if (!modelstate.isvalid )     {         throw new httpresponseexception(httpstatuscode.badrequest);     }    } 

this works great , if call view model has empty name fields in variables list, fails validation. however, when try validate unit test, runs validations on variableviewmodel , not recursively variableviewmodel. so, if pass in null variables, validation error if pass in empty string name, there no validation errors.

[testmethod] public void post_returns_httpresponseexception_with_empty_variable_name() {     var controller = new variablecontroller();     var viewmodel = new variabletemplateviewmodel                     {                         version = 1,                         variables = new list<variableviewmodel>                          {                              new variableviewmodel { name = "" }                         }                     };      var validationcontext = new validationcontext(viewmodel, null, null);      var validationresults = new list<validationresult>();     validator.tryvalidateobject(viewmodel, validationcontext, validationresults, true);     foreach (var validationresult in validationresults)     {         controller.modelstate.addmodelerror(validationresult.membernames.first(), validationresult.errormessage);     }      // assert  } 

i have tried removing/adding empty constructors , initializing variables inside variabletemplateviewmodel constructor. have tried using validator.tryvalidateobject on viewmodel.variables directly no avail.

does know how can fixed?

i have same problem , use solution. may you.

public void post(long id, [frombody]variabletemplateviewmodel model) {     if (!modelstate.isvalid && tryvalidatemodel(model.nestedmodel, "nestedmodel."))     {         throw new httpresponseexception(httpstatuscode.badrequest);     }    } 

try this, recursive validation using dataannotations


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -