I have a view similarly declared on this link.
<div id="personSection">
<!-- We have more than one personspecificmodel -->
@if (Model.PersonSpecificModels != null)
{
for (var i = 0; i < Model.PersonSpecificModels.Count; i++)
{
<div>
<div class="formColumn2">@Html.EditorFor(x => x.PersonSpecificModels[i].childProperty1)</div>
<div class="formColumn2">@Html.EditorFor(x => x.PersonSpecificModels[i].childProperty2)</div>
</div>
}
}
else
{
<!-- This is the form for the new user -->
<div>
<div class="formColumn2">@Html.EditorFor(x => x.PersonSpecificModels.childProperty1)</div>
<div class="formColumn2">@Html.EditorFor(x => x.PersonSpecificModels.childProperty2)</div>
</div>
}
The challenge that I have is that I have a model that have the following declaration:
public class PersonModel {
// Some properties, annotations, etc
[Required(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "ValidationErrorRequiredField")]
[StringLength(100, ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "StringLength")]
public string property1 { get; set; }
public List<PersonSpecificModel> PersonSpecificModels { get; set; }
public class PersonSpecificModel {
// Some declarations further
public string childProperty1 { get; set; }
public int childProperty2 { get; set; }
}
}
Before, there is a 1:1 relationship between PersonModel and PersonSpecificModel. One of the things that we need to do is to allow multiple PersonSpecificModels. Think of having a user having different bank account details.
The code that handles submit of this view is this:
[HttpPost, ValidateInput(false)]
public new ActionResult MyAction(PersonModel model)
{
if (ModelState.IsValid) // multiple PersonSpecificModels fail here
{
}
}
There is no issue when I am adding a new person to the model. The challenge that I have right now is that when a user have more than 1 PersonSpecificModels, the validation fails as it can't see properly the collection.
[Question] Would there be any way to properly validate the collection with the existing model definition? The model validation fails on the first line alone.