听起来您要求的不仅仅是视图模型。为了扩展神库的答案,这将是我在 VB 中的粗略/未经测试的方法。它不可能包罗万象,但希望能让您了解如何操作数据、将其传递给视图以及在回发时取回数据。
模型/数据库对象:
Public Class Service
Public Property ServiceID As Integer
Public Property Name As String
End Class
Public Class CustomerService
Public Property CustomerID As Integer
Public Property ServiceID As Integer
Public Property Selected As Boolean
Public Property LastDate As DateTime
Public Property ProposedDate As DateTime
End Class
视图模型:
Public Class ViewRow
Public Property ServiceID As Integer
Public Property Name As String
Public Property YesSelected As Boolean
Public Property NoSelected As Boolean
Public Property LastDate As String
Public Property ProposedDate As String
End Class
Public Class ViewModel
Public Property TableHeaders As String() = {"Services","Yes","No","Date of Last Service", "Proposed Date"}
Public Property ServiceDetails As List(Of ViewRow)
End Class
控制器:
Public Class HomeController
Inherits System.Web.Mvc.Controller
' Simulating EntityFramework
Protected db As New MyEntities
Function ServiceList() As ActionResult
Dim thisCustomerID As Integer
' *Set user's customer ID*
' Using a LINQ join to combine with other service information
Dim vm As New ViewModel With {
.ServiceDetails = ( _
From custService In db.CustomerService().ToList()
Join service In db.Service().ToList()
On custService.ServiceID Equals service.ServiceID
Where custService.CustomerID.Equals(thisCustomerID)
Select New ViewRow With {
.ServiceID = service.ServiceID,
.Name = service.Name,
.YesSelected = custService.Selected,
.NoSelected = Not custService.Selected,
.LastDate = custService.LastDate.ToString("MMM yyyy"),
.ProposedDate = custService.ProposedDate.ToString("MMM yyyy")
}).ToList()
}
' Passing to a strongly-typed view of type "ViewModel"
Return View("serviceList",model:=vm)
End Function
' This is where you post back, and data can be bound to type "ViewModel"
<HttpPost()> _
Function ServiceList(data As ViewModel) As ActionResult
' *Model Validation / Insert / Update*
' Refresh the page (if you want)
RedirectToAction("ServiceList","Home")
End Function
End Class
剃刀视图(serviceList.vbhtml):
@ModelType ViewModel
<div>
<table>
<tr>
@For Each head In Model.TableHeaders
@<th>@(head)</th>
Next
</tr>
@For Each detail In Model.ServiceDetails
@<tr id=@(detail.ServiceID)>
<td>@(detail.Name)</td>
<td>@(If(detail.YesSelected,"X",""))</td>
<td>@(If(detail.NoSelected,"X",""))</td>
<td>@(detail.LastDate)</td>
<td>@(detail.ProposedDate)</td>
</tr>
Next
</table>
</div>
要回发,您必须让 javascript 抓取数据输入到任何输入字段(我在这里没有包含任何内容),并构造一个 JSON 对象 - 带有适当的数据 - 反映参数控制器的发布操作。我提供了一个带有ViewModel 类型参数的示例。这意味着您的 JSON 字段必须与 ViewModel 模型中定义的字段相匹配,并且它们的值必须与相应属性的数据类型相匹配。 ASP.NET 将在回发时绑定数据。此外,ViewModel 很复杂,因此您可以发布ViewRow 的列表(用于多个记录更新)。要绑定它,您的 JSON 对象需要具有 ServiceDetails 属性,该属性包含一组对象,这些对象又具有 ServiceID、Name、YesSelected 等属性。