1

看法

@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 现在有公共设置器。问题似乎仍然存在。请看这张图片:

在此处输入图像描述

4

1 回答 1

3

问题是您将 SurveyQuestions 设为私有集吗?

- 旧答案-
你有 2 x (Html.BeginForm(Html.BeginForm 我曾经忘记将我的表单放在一个using做同样事情的语句中。

于 2013-02-25T08:59:07.590 回答