要更新一个包含多个元素的列表时,需要用到一个ViewModel。以下是一些示例代码,可供参考:
首先,需要定义一个ViewModel类,它包含一个List属性,该属性将用于存储元素列表:
public class MyViewModel
{
public List
接下来,需要在控制器中创建一个空的视图模型实例,并将其传递给视图:
public ActionResult Index()
{
var viewModel = new MyViewModel { Elements = new List
在视图中,可以使用循环来呈现元素列表。需要为每个元素定义一个表单,并在表单中使用HTML的隐藏字段来存储元素ID:
@model MyViewModel @using (Html.BeginForm()) { @for (int i = 0; i < Model.Elements.Count; i++) { @Html.HiddenFor(m => Model.Elements[i].Id) @Html.EditorFor(m => Model.Elements[i].Name) @Html.EditorFor(m => Model.Elements[i].Description) // Add other fields here... } }
当用户提交表单时,可以在控制器中将更改保存回数据库或其他持久性存储。以下示例演示了如何更新元素列表:
[HttpPost] public ActionResult Index(MyViewModel viewModel) { foreach (var element in viewModel.Elements) { // Update the element in the database... } return RedirectToAction("Index"); }