看法
@model Survey.Models.TakeSurveyViewModel
@{
Layout = "~/Views/Shared/_SiteLayout.cshtml";
}
<h2>SURVEY : @Model.Title</h2>
<h3>@Model.Description</h3>
<hr />
@using (Html.BeginForm("SubmitSurvey", "HomePage", FormMethod.Post, new { id = "surveyForm" }))
{
for (int index = 0; index < Model.SurveyQuestions.Count; index++)
{
@* Editor Template - Null result *@
@*SurveyQuestionModel item = Model.SurveyQuestions[index];
@Html.EditorFor(x => item);*@
<p>@Model.SurveyQuestions[index].QuestionText</p>
@Html.DropDownListFor(item => Model.SurveyQuestions[index].OptionId, new SelectList(Model.SurveyQuestions[index].Options, "OptionId", "OptionText"), string.Empty)
}
<input type="submit" value="SubmitSurvey" />
}
视图模型
public class TakeSurveyViewModel
{
public string Title { get; set; }
public string Description { get; set; }
public int SurveyId { get; set; }
public List<SurveyQuestionModel> SurveyQuestions { get; set; }
public TakeSurveyViewModel() { }
public TakeSurveyViewModel(int surveyId)
{
//Populate data - works ok.
}
}
下拉列表模型
public class SurveyQuestionModel
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
[Required(ErrorMessage = "Please select an option.")]
public int OptionId { get; set; }
public IEnumerable<QuestionOption> Options { get; set; }
}
该页面呈现良好,所有下拉菜单都带有正确的选项。每个 select 的 id 和 name 也是唯一的 -
id="SurveyQuestions_3__OptionId" name="SurveyQuestions[3].OptionId"
控制器动作
[HttpPost]
public ActionResult SubmitSurvey(TakeSurveyViewModel model)
{
return !ModelState.IsValid ? TakeSurvey(model.SurveyId) : null;
}
但是点击提交按钮,控制器动作模型为空。
编辑:删除了 2x HTML.BeginForm
编辑 2:SurveyQuestions 现在有公共设置器。问题似乎仍然存在。请看这张图片: