具有 Collections 和 Name 属性的 EditorFor
我正在尝试创建一个允许编辑多行数据的表单。我循环遍历并获取输入框进行渲染没有问题...我只是无法正确输出名称属性。
我知道,为了提交一个集合,您需要回发一个索引名称,其中索引从 0 开始连续。
<input name="Books[0].Title" />
<input name="Books[1].Title" />
and so on...
现在,我可以让 EditorFor 函数输出我的正确名称,并给出以下循环代码,
@For n = 0 To (Model.Books.Count - 1)
@Html.EditorFor(Function(m) Model.Books.Item(n).Title)
Next
我
<input name="Books[0].Title" />
<input name="Books[1].Title" />
and so on...
的问题是VS 显示以下警告
在 lambda 表达式中使用迭代变量可能会产生意外结果。相反,在循环中创建一个局部变量,并将迭代变量的值赋给它。
然而,当我将循环更改为时,
@For n = 0 To (Model.Books.Count - 1)
Dim item = Mode.Books.Item(n)
@Html.EditorFor(Function(m) item.Title)
Next
我有
<input name="$VB$Local_item.Title" />
<input name="$VB$Local_item.Title" />
and so on...
什么想法吗?我应该忽略这个警告吗?
谢谢。
- 贾森
I am trying to create a form that allows the editing of multiple rows of data. I have no problem looping through and getting input boxes to render...I just cannot get the name attributes to output correctly.
I know that in order to submit a collection you need to post back an indexed name where the index is sequential starting at 0.
<input name="Books[0].Title" />
<input name="Books[1].Title" />
and so on...
Now, I can get the EditorFor function to output my proper name with given the following loop code
@For n = 0 To (Model.Books.Count - 1)
@Html.EditorFor(Function(m) Model.Books.Item(n).Title)
Next
giving me
<input name="Books[0].Title" />
<input name="Books[1].Title" />
and so on...
My problem is VS shows the following warning
Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.
Yet when I change the loop to
@For n = 0 To (Model.Books.Count - 1)
Dim item = Mode.Books.Item(n)
@Html.EditorFor(Function(m) item.Title)
Next
I get
<input name="$VB$Local_item.Title" />
<input name="$VB$Local_item.Title" />
and so on...
Any thoughts? Should I just ignore the warning?
Thanks.
- Jason
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MVC 的工作原理是实际分解 lambda 表达式,并查看它的组成部分。它不只是执行 lambda 并获得结果。因此,您需要实际使用 lambda 中的模型参数才能使其正常工作。这应该适合你:
MVC works by actually breaking apart the lambda expression, and seeing what it's made of. It doesn't just execute the lambda and get the result. So you need to actually use the model parameter in the lambda for it to work. This should do it for you: