【发布时间】:2012-04-23 22:52:33
【问题描述】:
我有一个包含几行数据的表,我需要将这些数据返回给控制器。在我看来,我最初通过选择时间段并单击按钮来加载表格。该表加载了我所有的相关记录,但我的一个表单元格包含一个下拉列表。所以我应该能够在下拉菜单中进行选择,点击“更新”,我的控制器会保存更改。
所以在我尝试保存之前一切正常。发送到控制器的模型完全为空。我绑定到表格单元格的列表属性返回到控制器 null。
@ModelType SuperViewModel
//We need this a view model in order to store a List of the models in the table
@Using (Html.BeginForm())
@For Each i in Model.CompleteList
Dim currentItem = i //MVC auto-generated extra declarations. Seems redundant to me but it works.
@<table>
<tr>
<td>@Html.DisplayFor(function(Model)currentItem.Name)</td>
<td>@Html.DisplayFor(function(Model)currentItem.SampleTime)</td>
<td>@Html.DropDownListFor(function(Model)currentItem.WorkTime, ViewBag.WorkTimeList)</td>
</tr>
Next
</table>
<input name="submit" type="submit" value="Update"/>
End Using
//Controller
<HttpPost()>
function Save(vmodel as SuperViewModel, submit as String) as ActionResult //NOTE: submit parameter is used because we have two submit buttons but its not relevant here
if submit = "Update"
db.Entry(vmodel.CompleteList).State = EntityState.Modified//Here the exception is throw because our list is null at this point even tho its tied to the model in the view.
db.SaveChanges()
end if
End Function
注意:这是用 VB.NET 编写的,但欢迎 C# 帮助。我熟悉 MVC 中的两种语言。
【问题讨论】:
-
SuperViewModel 是如何定义的?
-
其中有几个属性,但适用于此的是“CompleteList”,它是一个列表(另一个模型)。其他模型是由实体框架根据我们的数据库表生成的。
-
在
End Using之前是否缺少Next来关闭For Each?另外,你能添加一些视图呈现的标记吗?
标签: c# asp.net-mvc vb.net razor viewmodel