MVC:将多行数据返回给控制器

本文关键字:返回 控制器 数据 MVC | 更新日期: 2023-09-27 18:31:59

我有一个表,其中包含需要返回给控制器的几行数据。在我看来,我最初通过选择时间段并单击按钮来加载表格。该表加载了我所有相关的记录,但我的一个表格单元格包含一个下拉列表。所以我应该能够在下拉列表中单击"更新"进行选择,然后我的控制器保存更改。

所以一切都有效,直到我尝试保存。发送到控制器的模型完全为空。我绑定到表单元格的列表属性返回到控制器 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中的两种语言。

MVC:将多行数据返回给控制器

您需要使用

for 迭代器,并让视图使用 HTML 元素的索引元素。我不知道 VB.NET 语法,下面是 c# 示例。这允许模型绑定程序正确确定视图模型中的元素,以便它可以在回发时重新填充视图模型。

<table>
 @For(var i = 0; i < Model.CompleteList.Count; i++) 
{
 <tr>
 <td>@Html.DisplayFor(Model.CompleteList[i].Name)</td>
 <td>@Html.DisplayFor(Model.CompleteList[i]..SampleTime)</td>
 <td>@Html.DropDownListFor(Model.CompleteList[i]..WorkTime, ViewBag.WorkTimeList)</td>
 </tr>
}
 </table>

然后,您的发布方法应该可以正常工作。

由于参数名称中的一些冲突,它可能返回 null(使用的参数名称也必须在其他位置使用)。试试这个

<input name="subButton" type="submit" value="Update"/>

和改变

function Save(vm as SuperViewModel, subButton as String) as ActionResult

我需要在DropDownListFor生成的标记中看到名称,但我怀疑这是因为使用currentItem您绑定了CompleteList类型,但您的控制器方法需要完整的SuperViewModel类型。在您显示的代码中,没有任何地方看到您绑定到SuperViewModel类型。

尝试将控制器方法更改为:

<HttpPost()>
 function Save(currentItem as CompleteList, 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).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

应使用下拉列表列表中的选定值填充WorkTime属性。

编辑:更改了参数名称以匹配绑定名称。