无论我在post方法中做什么,模型都将Answers视为null。
index.cshtml
@using WebPortal.Classes
@using WebPortal.Models
@model WebPortal.Models.QuestionsAnswersViewModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
@using (Html.BeginForm("index", "QuestionFormResponses", FormMethod.Post))
{
@Html.AntiForgeryToken()
if (Model != null)
{
string category = "";
string column = "";
foreach (Answer answer in Model.Answers)
{
if (answer.Question.QuestionCategory.Category != category)
{
category = answer.Question.QuestionCategory.Category;
<h1>@category</h1>
}
if (answer.QuestionCategoryColumn.ColumnName != column)
{
column = answer.QuestionCategoryColumn.ColumnName;
<h4>@column</h4>
}
Html.HiddenFor(x => x.Answers);
<p>@answer.Question.QuestionText: </p>
<input type="text" name="@answer.Id" value="@answer.QuestionAnswer"/>
}
<input type="submit" value="Submit" class="btn btn-default"/>
}
查看模型
namespace WebPortal.Models
{
public class QuestionsAnswersViewModel
{
public List<Answer> Answers { get; set; }
}
}
发布方法
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(QuestionsAnswersViewModel m)
{
答案模型
namespace WebPortal.Models
{
public class Answer
{
public int Id { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
public int QuestionFormResponseId { get; set; }
public virtual QuestionFormResponse QuestionFormResponse { get; set; }
public int QuestionCategoryColumnId { get; set; }
public virtual QuestionCategoryColumn QuestionCategoryColumn { get; set; }
public object QuestionAnswer { get; set; }
}
}
我在帖子的第一行放置一个断点,然后去查看m中的内容。 m总是将Answers设置为null。即使视图模型在前端到达前端时已经满了,前端也可以显示其中的内容。
答案 0 :(得分:0)
编辑:
将我的前端代码更改为以下内容。前端看起来很糟糕但现在回发了
@using (Html.BeginForm("index", "QuestionFormResponses", FormMethod.Post))
{
@Html.AntiForgeryToken()
if (Model != null)
{
for (int i = 0; i < Model.Answers.Count; i++)
{
<table>
<tr><th>
@Html.DisplayFor(a => a.Answers[i].QuestionCategoryColumn.QuestionCategory.Category)
</th></tr>
<tr>
<td>@Html.DisplayFor(a => a.Answers[i].QuestionCategoryColumn.ColumnName)</td>
<td>@Html.DisplayFor(a => a.Answers[i].Question.QuestionText)</td>
<td>@Html.TextBoxFor(a => a.Answers[i].QuestionAnswer)</td>
</tr>
</table>
}
<input type="submit" value="Submit" class="btn btn-default"/>
}
}