模型绑定列表
的控制器操作
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)
{
...
}
我有一个像view> 这样 看起来像:
<% for (int i = 0; i < Model.Count; i++) { %>
<div>
<%= Html.Hidden(i.ToString() + ".Id") %>
<%= Model[i].Question %>
<%= Html.TextBox(i.ToString() + ".Answer") %>
</div>
<% } %>
显然这个观点行不通。 我只是无法访问视图中的列表。
这方面的文档也已经过时了,模型绑定列表的很多功能似乎在测试版中都发生了变化。
I got a controller action like
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)
{
...
}
the view> looks like:
<% for (int i = 0; i < Model.Count; i++) { %>
<div>
<%= Html.Hidden(i.ToString() + ".Id") %>
<%= Model[i].Question %>
<%= Html.TextBox(i.ToString() + ".Answer") %>
</div>
<% } %>
Obviously this view doesn't work. I'm just not able access the list in the view.
The documentation for this also is outdated, it seem a lot of the functionality around modelbinding lists where changed in the beta.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为斯科特·汉塞尔曼的帖子可能给出了答案。 然而,您似乎试图通过在帖子
...0.Answer=answer...
中返回来将视图引用绑定到匿名对象,您应该将您的字段绑定到`列出参考答案[index].Answer 的答案。
尝试以下操作:
理查德
I think that Scott Hanselman's post probably holds the answer. However it appears that you are trying to tie you view references to an anonymous object by returning in the post
...0.Answer=answer...
You should instead I believe be tying your fields to the `List answers refering to the answers[index].Answer.
Try the following:
Richard
看看这个和这个问题。 还有这篇博文。
编辑:至于访问视图中的模型。 您确定您声明了以下属性吗?
Take a look at this and this question. Also this blog post.
Edit : As for accessing the model in the view. Are you sure you declared your with the following attribute?
答案是不使用 html 助手。
不是很漂亮,但是很有效。 重要的是 Name 和 Id 需要不同。
名称允许包含“[”、“]”,但 id 不允许。
the answer is not to use the html helpers.
Not very pretty, but works. The important thing is that Name and Id need to be different.
Name is allowed to have "[", "]" but id isn't.