MVC Complex Object Binding
I'm using MVC, Have the following Model
public class Questionnaire
{
public string Name { get; set; }
public List<Question> Questions { get; set; }
}
and Question class is :
public class Question
{
public int QuestionNumber { get; set; }
public string Body { get; set; }
public IList<Option> Options { get; set; }
//public IEnumerable<CreativeFactory.Option> OptionsTemp { get; set; }
public Guid? QuestionnaireId { get; set; }
public Guid? SelectedOption { get; set; }
public int? SelectedEmployeeId { get; set; }
}
In my View I do foreach, and partially render a view
% Html.BeginForm("Submit", "Questionnaire", FormMethod.Post); %>
<%
foreach (var q in Model.Questions)
{
Html.RenderPartial("Question", q);
}
%>
<input type="submit" name="submit" value="submit" />
<% Html.EndForm(); %>
My problem is the passed model to my action is always null
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Submit(Questionnaire m)
{
}
EDIT 1: Well, My Partial View Co开发者_如何学JAVAde is :
<%
foreach (var option in Model.Options)
{%>
<p/>
<%= Html.RadioButtonFor(x => x.SelectedOptionId, option.QuestionId, new { id = "test" + option.ID })%>
<%
}
%>
Even in the debugging Mode, I can't find my collection in the Form instance so even Custom Binding dosn't solve the problem, because the collection is not exist
any idea please?
I think you have to make Questionnaire
implement ICollection<Question>
and then follow these detailed instructions in Phil Haack's post. If you don't want Questionnaire
to implement ICollection<Question>
, I think you need to implement a custom model binder of the Questionnaire
type.
This is the code for your partial, not tested. I assumed a zero based QuestionNumber:
<input type="hidden" name="Questions[<%= Model.QuestionNumber %>].QuestionNumber" value="<%= Model.QuestionNumber %>" />
<% foreach (var option in Model.Options) { %>
<input type="radio" name="Questions[<%= Model.QuestionNumber %>].SelectedOptionId" value="<%= option.ID %>" /><%= option.Text %>
<% } %>
Complete answer: MVC post a list of complex objects which contains Phil Haack's solution and another one too:
@for (var itemCnt = 0; itemCnt < Model.Questions.Count(); itemCnt++)
{
@Html.TextBoxFor(m => Model.Questions[itemCnt].Body)
....
@Html.HiddenFor(m => Model.Questions[itemCnt].QuestionNumber )
}
精彩评论