我有一个像
这样的控制器动作public class Question {
public int Id { get;set; }
public string Question { get;set; }
public string Answer { get;set; }
}
public ActionResult Questions()
{
return View(GetQuestions());
}
public ActionResult SaveAnswers(List<Question> answers)
{
...
}
视图&gt;看起来像:
<% for (int i = 0; i < Model.Count; i++) { %>
<div>
<%= Html.Hidden(i.ToString() + ".Id") %>
<%= Model[i].Question %>
<%= Html.TextBox(i.ToString() + ".Answer") %>
</div>
<% } %>
显然这种观点不起作用。我只是无法访问视图中的列表。
这方面的文档也已过时,似乎很多关于模型绑定列表的功能在测试版中发生了变化。
答案 0 :(得分:0)
查看this和this question。还this blog post。
编辑:至于在视图中访问模型。您确定使用以下属性声明了您的身份吗?
<%@ Page Language="C#"
Inherits="System.Web.Mvc.ViewPage<List<Namespace.Question>>" %>
//Assuming the GetQuestions() method returns a list of question objects.
答案 1 :(得分:0)
我认为Scott Hanselman的帖子可能就是答案。但是,您似乎试图通过返回帖子...0.Answer=answer...
相反,我应该相信你的字段与`列出答案参考答案[索引]。答案。
尝试以下方法:
<% for (int i = 0; i < Model.Count; i++) { %>
<div>
<%= Html.Hidden("answer["+i.ToString() + "].Id", Model["+i.ToString() + "].Id) %>
<%= Model[i].Question %>
<%= Html.TextBox("answer["+i.ToString() + "].Answer", Model["+i.ToString() + "].Answer) %>
</div>
<% } %>
理查德
答案 2 :(得分:0)
答案是不使用html助手。
<% for (int i = 0; i < Model.Count; i++) { %>
<div>
<input type="hidden" name="answers[<%= i %>].Id" id="answers_<%= i %>_Id" value="<%= Model[i].Id %>" />
<input type="text" name="answers[<%= i %>].Answer" id="answers_<%= i %>_Answer" value="<%= Model[i].Answer %>" />
</div>
<% } %>
不是很漂亮,但有效。重要的是Name和Id需要不同。 名称允许有“[”,“]”但id不是。