Complex ViewModel 在表单 post 上为空

Complex ViewModel is null on form post

我在使用复杂的 ViewModel 构建问卷时开发的系统有问题。提交表单时,返回的 ViewModel 为空。

我看到过关于 viewmodel 的参数名称与 ViewModel 本身不同以及 ViewModel 中的一些参数名称导致问题的帖子,但我看不出有什么不妥。

有什么想法吗?

谢谢 西蒙

ViewModel 看起来像这样:

public class SurveysViewModel
{
    public Survey SurveyDetails { get; set; }
    [AdditionalMetadata("HideLabel", true)]
    public List<QuestionSet> SurveyQuestions { get; set; }
}

他们里面的类是这样的:

public class Survey
{
    public int Id { get; set; }
    public string SurveyName { get; set; }
    public int IntroId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public bool Active { get; set; }
    public string IntroName { get; set; }
    public string Intro { get; set; }
    public string Conclusion { get; set; }
}

public class QuestionSet
{
    public int? SubQuestionOf { get; set; }
    public int Order { get; set; }
    public bool RepeatPerUser { get; set; }
    public int Id { get; set; }
    public string QuestionText { get; set; }
    public string Q_Text { get; set; }
    public string SubText { get; set; }
    public string TableTitle { get; set; }
    public List<Answer> Answers { get; set; }
    public string Format { get; set; }
    public string OptionsGroup { get; set; }
    public string DBViewName { get; set; }
    public string Header { get; set; }
    public int? Minimum { get; set; }
    public int? Maximum { get; set; }
    public int? Interval { get; set; }
    public int SelectedOption { get; set; }
    public bool Selected { get; set; }
}

控制器中的Post方法如下:

    [HttpPost]
    [ValidateAntiForgeryToken]
    [ActionName("CompleteSurvey")]
    public ActionResult CompleteSurvey_Post(SurveysViewModel vm)
    {
        if (ModelState.IsValid)
        {
          //Do something in here
        }
    }

但是 ViewModel (vm) 将这两个部分显示为空。

我应该补充一点,问题集中的问题是继承自 QuestionSet 的各种类型(例如下拉列表或范围输入),例如:

public class QuestionSet_DropDown : QuestionSet
{
    public QuestionSet_DropDown(QuestionSet question)
    {
        Header = question.Header;
        Id = question.Id;
        QuestionText = question.QuestionText;
        Q_Text = question.Q_Text;
        AllowMultiSelect = false;

    }
    public List<Answer> Options { get; set; }
    public bool AllowMultiSelect { get; set; }
}

@model SurveysViewModel

<h1>Survey Page</h1>
<form action="/PublicAuthSurvey/CompleteSurvey" method="post" class="form-horizontal">
  @Html.AntiForgeryToken()
  <div class="survey">
     @{ var questions = Model.SurveyQuestions; }
      @Html.EditorForModel(questions)
  </div>
  <input class="btn btn-lg btn-success" type="submit" value="Submit Results" />
</form>

感谢您到目前为止的评论。我终于成功了。

我混合使用了嵌套复杂类型、继承和自定义编辑器模板,当您查看页面上的标记时,创建的一些输入没有正确映射回模型。

如果其他人正在阅读本文以寻求解决方案,请使用开发人员工具检查您的编辑器模板创建的输入的名称,并确保它们正确映射回您的模型。对我来说,一种类型没有正确映射,所以整个模型被返回为 null。

脱了很多头发后,我想我就快到了!

谢谢 西蒙