[英]MVC model binding to edit a list not working
I can't figure out why this won't work. 我不知道为什么这行不通。 Everything I've read (both here and across the web) says this is how to bind to a list for editing but I'm not having any success.
我读过的所有内容(无论是在这里还是在整个网络上)都表示这是如何绑定到列表进行编辑的,但是我没有成功。 I have two problems:
我有两个问题:
The HTML form elements emitted by the view are not being indexed (each one is named "Qty" and "BoxID" instead of "[0].Qty" and "[0].BoxID"). 该视图发出的HTML表单元素未编入索引(每个都被命名为“ Qty”和“ BoxID”,而不是“ [0] .Qty”和“ [0] .BoxID”)。 Everything I've read on this subjuct says the HTML.EditorFor and HiddenFor helpers should pick this up automatically.
我在该主题上阅读的所有内容都表明HTML.EditorFor和HiddenFor帮助器应自动将其选中。
Even when I manually change the view to spit out the correct HTML (form elements with the right names) model binding isn't happening correctly and the collection parameter in the controller action method is null. 即使当我手动更改视图以吐出正确的HTML(具有正确名称的表单元素)时,模型绑定也不会正确发生,并且控制器action方法中的collection参数为null。
Any ideas? 有任何想法吗? Am I doing something wrong?
难道我做错了什么?
Here's the view: 这是视图:
@ModelType IEnumerable(of HonorBox)
@Code
ViewData("Title") = "Index"
End Code
<h2>Index</h2>
@Html.BeginForm("Index", "HonorBoxes")
@Html.AntiForgeryToken()
@For x = 0 To Model.Count - 1
@<tr>
<td>
@Html.DisplayFor(Function(i) Model(x).BoxID)
@Html.HiddenFor(Function(i) Model(x).BoxID)
</td>
<td>
@Html.TextBoxFor(Function(i) Model(x).Qty)
@Html.ValidationMessageFor(Function(i) Model(x).Qty)
</td>
</tr>
Next
And these are the controller methods: 这些是控制器方法:
Function Index() As ActionResult
Dim hb = From h In db.honorBoxes Select h Where Not h.Filled And Not h.Hold
Return View(hb.ToList())
End Function
<HttpPost>
Function Index(boxes As IEnumerable(Of HonorBox)) As ActionResult
If ModelState.IsValid Then
For Each box In boxes
Dim cbox = db.honorBoxes.Find(box.BoxID)
If Not IsDBNull(box.Qty) AndAlso cbox.Qty <> box.Qty Then
cbox.Qty = box.Qty
cbox.Filled = True
End If
Next
db.SaveChanges()
End If
Return RedirectToAction("Index")
End Function
Finally here's the model 最后是模型
Public Class HonorBox
<Key> Public Property BoxID As Integer
Public Property AssetID As Nullable(Of Integer)
Public Property Asset As Asset
Public Property BoxType As String
Public Property Hold As Nullable(Of Boolean)
Public Property Filled As Nullable(Of Boolean)
Public Property Qty As Nullable(Of Integer)
End Class
In order for the model binder to pick it up the model type needs to be of type List
not IEnumerable
. 为了使模型绑定器能够拾取它,模型类型需要为
List
not IEnumerable
类型。
Changing it to this will work: 将其更改为此将起作用:
@ModelType List(of HonorBox)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.