提交时ASP.NET MVC 3模型为null

时间:2013-02-25 08:55:39

标签: asp.net asp.net-mvc-3

查看

@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.
        }
    }

DropDownList模型

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; } 
    }

页面呈现正常,所有下拉列表都有正确的选项。每个选择的ID和名称也是唯一的 -
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现在有公共制定者。问题似乎仍然存在。请看这个图片:

enter image description here

1 个答案:

答案 0 :(得分:3)

您有SurveyQuestions是私有集的问题吗?

- 答案 -
你有2个     (Html.BeginForm(Html.BeginForm 我曾经忘记在using声明中使用我的表格做同样的事情。