MVC模型绑定编辑列表不起作用

时间:2014-09-25 16:03:53

标签: asp.net asp.net-mvc vb.net asp.net-mvc-5 entity-framework-6.1

我无法弄清楚为什么这不起作用。我读过的所有内容(无论是在这里还是在网上)都说这是如何绑定到列表进行编辑但我没有取得任何成功。我有两个问题:

  1. 视图发出的HTML表单元素未被索引(每个元素都被命名为“Qty”和“BoxID”而不是“[0] .Qty”和“[0] .BoxID”)。我在这个子项目中读过的所有内容都说HTML.EditorFor和HiddenFor帮助器应该自动选择它。

  2. 即使我手动更改视图以吐出正确的HTML(具有正确名称的表单元素),模型绑定也不会正确发生,并且控制器操作方法中的collection参数为null。

  3. 有什么想法吗?我做错了吗?

    以下是观点:

    @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
    

1 个答案:

答案 0 :(得分:1)

为了让模型绑定器选择它,模型类型必须是List而不是IEnumerable

将其更改为此将起作用:

@ModelType List(of HonorBox)