【发布时间】:2018-12-19 14:34:59
【问题描述】:
我正在使用复杂的 ViewModel 构建调查问卷的系统遇到问题。提交表单时,返回的 ViewModel 为 null。
我看到过关于 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) 将这两个部分显示为 null。
我应该补充一点,问题集中的问题是从 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>
【问题讨论】:
-
这完全取决于您提交数据的方式。将此添加到问题中
-
请显示您的查看代码以查看您的查看页面是否导致问题。确保包含
@model指令和包含回发触发器(例如提交按钮)的表单内容。 -
我已经添加了视图 - 正如您所看到的,它非常简单,但我有针对我的问题类型的自定义编辑器。
-
只考虑我的 EditorForModel 只是使用我模型的问题元素。是这个原因吗?
-
是的,我想是的。我很确定您至少需要提交调查类型的 ID 号以及表格的其余部分。它不一定要显示,它可以在隐藏的 div 或类似的地方。我最近为此找到了一个帮助类,我会尝试为您查找 URL。
标签: asp.net-mvc asp.net-mvc-4 model-view-controller