I have a RegisterModel, composed of 5 SecretQuestionAndAnswerModel models
public class RegisterModel
{
public SecretQuestionAndAnswerModel SecretQuestion1 { get; set; }
public SecretQuestionAndAnswerModel SecretQuestion2 { get; set; }
public SecretQuestionAndAnswerModel SecretQuestion3 { get; set; }
public SecretQuestionAndAnswerModel SecretQuestion4 { get; set; }
public SecretQuestionAndAnswerModel SecretQuestion5 { get; set; }
}
and
public class SecretQuestionAndAnswerModel
{
public SecretQuestionTypeModel Type { get; set; }
[Required(ErrorMessage = "Please choose a question.")]
public int Id { get; set; }
public string Question { get; set; }
[Required]
[StringLength(20)]
public string Answer { get; set; }
[Display(Name = "Select Question")]
public IEnumerable<SelectListItem> DefaultQuestions { get; set; }
}
On my main Register.cshtml, I include each question like this:
@Html.Partial("_QuestionAndAnswer", Model.SecretQuestion1, new ViewDataDictionary { { "Index", 1 }})
and that partial looks like:
<div class="input">
@{
@Html.DropDownListFor(m => Model.Id, Model.DefaultQuestions, "(Please choose one)")
@Html.ValidationMessageFor(m => Model.Id)
@Html.TextBoxFor(m => m.Answer)
@Html.ValidationMessageFor(m => m.Answer)
}
</div>
But on validation, all 5 questions behave as one: in other words if I select a question and type in an answer for the 1st secret question then they all pass validation, and vice versa…
Also, on posting to the HttpPost Register method
public ActionResult Register(RegisterModel model) { ...
the model.SecretQuestion1 is always null. All of them are. How do you do this sort of nested model-binding? I thought this would work ok.
The reason is pretty obvious if you look at the generated HTML. Each item has the same ID, and the same name. There is no easy way for the model binder to tell which is which.
This is a prime example of the difference between a partial view, and a template. Templates have extra logic to deal with this situation.
You should, instead create a SecretQuestionAndAnswerModel template and use
If you are unsure of how templates work, read this:
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html