我有一个包含几行数据的表,我需要将这些数据返回给控制器。在我看来,我最初通过选择时间段并单击按钮来加载表格。该表加载了我所有的相关记录,但我的一个表单元格包含一个下拉列表。所以我应该能够在下拉菜单中进行选择,点击“更新”,我的控制器会保存更改。
所以一切正常,直到我尝试保存。发送到控制器的模型完全为空。我绑定到表格单元格的列表属性返回到控制器 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 中的两种语言。