ASP.NET core MVC 向模型中添加list
时间: 2023-11-25 17:06:13 浏览: 174
要向 ASP.NET Core MVC 模型中添加列表,可以使用 C# 的 List 类型。以下是一个示例:
1. 首先,在模型类中定义一个 List 属性,如下所示:
```csharp
public class MyModel
{
public List<string> MyList { get; set; }
}
```
2. 在视图中,使用 HTML 的 form 元素来提交表单数据。在表单中,可以通过使用 for 循环和 Html.HiddenFor() 方法来将列表中的每个元素都作为隐藏字段提交。例如:
```html
@model MyModel
@using (Html.BeginForm())
{
for (int i = 0; i < Model.MyList.Count; i++)
{
@Html.HiddenFor(m => m.MyList[i])
}
<input type="submit" value="Submit" />
}
```
3. 在控制器的 POST 方法中,可以通过模型绑定来获取提交的列表数据。例如:
```csharp
[HttpPost]
public IActionResult MyAction(MyModel model)
{
// Access the list data here
List<string> myList = model.MyList;
// Do something with the list data...
return RedirectToAction("Index");
}
```
这样就可以向 ASP.NET Core MVC 模型中添加列表了。
阅读全文
相关推荐



















