我已经解决了我在使用 asp.net mvc4 应用程序时遇到的问题并对其进行了简化,以便我可以将其发布在这里。我的基本问题是我试图将项目列表发送到我的视图并编辑任何项目的复选框,然后将列表项目发送回控制器并最终保存到数据库。当我将列表发送回控制器时,现在编写代码的方式是一个空值,就像它从未实例化一样。
代码如下:
Public Class Person
Property ID As Integer
Property Name As String
Property Active As Boolean
End Class
在控制器中,我调用了一个名为 BuildPeople 的类,它实际上只是构建要传递的列表的一种方式:
Public Class BuildPeople
Public Function GetPersonList() As List(Of Person)
Dim personList As New List(Of Person)
personList.Add(GetPerson(1, "Chris", True))
personList.Add(GetPerson(2, "Ken", True))
personList.Add(GetPerson(3, "Jen", True))
Return personList
End Function
Private Function GetPerson(id As Integer, name As String, active As Boolean) As Person
Dim p As New Person
p.ID = id
p.Name = name
p.Active = active
Return p
End Function
End Class
控制器只有编辑能力:
Imports System.Web.Mvc
Public Class PeopleController
Inherits Controller
' GET: /People
Function Index() As ActionResult
Return View()
End Function
' GET: /People/Edit/5
Function Edit() As ActionResult
Dim bp As New BuildPeople
Dim model As New List(Of Person)
model = bp.GetPersonList
ViewData.Model = model
Return View()
End Function
' POST: /People/Edit/5
<HttpPost()>
Function Edit(ByVal listPeople As List(Of Person)) As ActionResult
Try
' TODO: Add update logic here
If listPeople Is Nothing Then
'Don't want to end up here
Return View()
Else
'Want to end up here
Dim i As Integer = listPeople.Count
Return View()
End If
Catch
Return View()
End Try
End Function
End Class
然后视图如下:
@ModelType List(Of Person)
@Code
ViewData("Title") = "Edit"
Layout = "~/Views/Shared/_Layout.vbhtml"
End Code
<h2>Edit</h2>
@Using (Html.BeginForm())
@Html.AntiForgeryToken()
@<div class="form-horizontal">
<h4>Person</h4>
<hr />
@For Each item In Model
Dim currentitem = item
@Html.HiddenFor(Function(model) currentitem.ID)
@Html.EditorFor(Function(model) currentitem.Name)
@Html.EditorFor(Function(model) currentitem.Active)
Next
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
End Using
<div>
@Html.ActionLink("Back to List", "Index")
</div>