[英]MVC model binding to edit a list not working
我不知道為什么這行不通。 我讀過的所有內容(無論是在這里還是在整個網絡上)都表示這是如何綁定到列表進行編輯的,但是我沒有成功。 我有兩個問題:
該視圖發出的HTML表單元素未編入索引(每個都被命名為“ Qty”和“ BoxID”,而不是“ [0] .Qty”和“ [0] .BoxID”)。 我在該主題上閱讀的所有內容都表明HTML.EditorFor和HiddenFor幫助器應自動將其選中。
即使當我手動更改視圖以吐出正確的HTML(具有正確名稱的表單元素)時,模型綁定也不會正確發生,並且控制器action方法中的collection參數為null。
有任何想法嗎? 難道我做錯了什么?
這是視圖:
@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
這些是控制器方法:
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
最后是模型
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
為了使模型綁定器能夠拾取它,模型類型需要為List
not IEnumerable
類型。
將其更改為此將起作用:
@ModelType List(of HonorBox)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.