【问题标题】:ASP.NET MVC 3 Model null on submit提交时 ASP.NET MVC 3 模型为空
【发布时间】:2013-02-10 09:01:46
【问题描述】:

查看

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

页面呈现良好,所有下拉菜单都带有正确的选项。每个 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 现在有公共设置器。问题似乎仍然存在。请看这张图片:

【问题讨论】:

  • 你有 2 个 @Html.BeginForm? 这是故意的吗?
  • 删除了额外的,提交时仍然为空。

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


【解决方案1】:

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

-旧答案-
你有 2 x (Html.BeginForm(Html.BeginForm 我曾经忘记在 using 声明中包含我的表单,它做了同样的事情。

【讨论】:

  • 刚刚删除了 1x BeginForm 并且它仍然为空:(
  • 好的,在将其公开时,将创建空选项元素,但所有内容仍然为空。第二次编辑 - 问题的屏幕截图。
  • 当您的表单回发时,将为您的模型设置的唯一值将是选项列表和选项 ID。除非您的表单中存在其他项目,否则不会提交任何其他项目。甚至没有选项文本。
  • 解决选项文本的一种方法是将所选文本存储在下拉列表旁边的隐藏字段中。 javascript onchange 代码...
  • 将其保存为隐藏字段。您的模型将仅填充从提交的表单输入元素发布的内容。
猜你喜欢
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
相关资源
最近更新 更多