【发布时间】:2011-07-26 11:52:34
【问题描述】:
我的代码:
public ActionResult Index()
{
IndexViewModel indexViewModel = new IndexViewModel();
indexViewModel.Questions = GetQuestions();
//Look here, I need to associate a answer for each question, i make a array with the number of questions, this seems a good idea?
indexViewModel.Answers = new Answer[indexViewModel.Questions.Count];
return View(indexViewModel);
}
[HttpPost]
public ActionResult Index(IndexViewModel indexViewModel)
{
if (ModelState.IsValid)
{
//The problem is here:
//The **Questions** property in IndexViewModel comes empty
//and I need to associate Questions and Answers
...
context.SaveChanges();
return RedirectToAction("Index");
} else
{
indexViewModel.Questions = GetQuestions();
indexViewModel.Answers = new Answer[indexViewModel.Questions.Count];
return View(indexViewModel);
}
}
private IList<Question> GetQuestions()
{
return context.Question.ToList();
}
问题在于代码 cmets。谢谢。
更新:
我的 HTML:
@using (Html.BeginForm()) {
<fieldset>
@Html.ValidationSummary(false, "Fix the erros:")
@for (int i = 0; i < Model.Questions.Count; i++)
{
<div class="editor-label">
@Html.DisplayFor(model => model.Questions[i].Description)
</div>
<div class="editor-field">
@Html.LabelFor(model => model.Answers[i].Score)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Answers[i].Score)
</div>
}
<p>
<input type="submit" value="Send" />
</p>
</fieldset>
}
【问题讨论】:
-
这取决于你如何呈现你的 html 表单。 Asp.net mvc 默认模型绑定器接受用于绑定对象集合的特定格式。
-
MVC 模型绑定输入。您的 html 标记中没有与问题相关的输入标签。快速而肮脏的解决方案是 @Html.HiddenFor(x=>x.Questions[i].Description for each question field。
-
@Arnis 我不想要一个肮脏的解决方案,如果你能发布一个完整而干净的解决方案,我将非常感激。
-
这很脏,因为您需要通过 HTTP 传递实体状态。我怀疑您没有在客户端对其进行修改,因此不需要首先将其传递给客户端。我的意思是 - 这不是关于回答问题(与编辑问题描述相反)吗?将问题存储在会话或数据存储中,并仅传递给客户端标识符。
标签: .net asp.net-mvc asp.net-mvc-3 razor