我有一张表,其中有几行数据需要返回给控制器。在我看来,我最初通过选择一个时间段并点击一个按钮来加载表格。该表加载所有相关记录,但我的一个表格单元格包含一个下拉列表。所以我应该可以在下拉菜单中选择“更新”,我的控制器保存更改。MVC:将多行数据返回给控制器
所以一切正常,直到我尝试并保存。发送给控制器的模型是完全无效的。我绑定到表格单元格的列表属性返回给控制器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是如何定义的? – 2012-04-23 23:03:18
它有几个属性,但在这里适用的是“CompleteList”,它是一个List(Of AnotherModel)。实体框架基于我们的数据库表生成的那个其他模型。 – ExceptionLimeCat 2012-04-23 23:08:26
在“End Using”关闭“For Each”之前是否存在'Next'?另外,你可以添加一些由视图呈现的标记吗? – 2012-04-23 23:33:26