c# - 将嵌套集合从 MVC 视图发布到控制器
问题描述
我有一个列表,Line
其中包含一个列表RowLane
,对于每一行它都有一个列表RowLane
。
结果是这样的:
风景
<table class="table">
<tr>
<th>
@Html.DisplayName("Nome do Grupo")
</th>
<th>
@Html.DisplayName("Linhas")
</th>
<th></th>
</tr>
@using (Html.BeginForm("Forms", "ProcessLane", FormMethod.Post))
{
foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.GroupName)
</td>
<td>
@{
foreach (var t in item.RowLane)
{
@Html.CheckBoxFor(model => t.IsChecked)
@Html.DisplayFor(modelItem => t.LaneName)
}
}
</td>
<td>
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Adicionar" class="btn btn-default" />
</div>
</td>
</tr>
}
}
和类:
public class Line
{
public int IdGroup { get; set; }
public string GroupName { get; set; }
public List<RowLane> RowLane { get; set; }
}
public class RowLane
{
public string IdLane { get; set; }
public string LaneName { get; set; }
public bool IsChecked { get; set; }
}
我只需要从所选行中收集 GroupID 和所有复选框。
解决方案
在您的场景中,要将所选行的数据从视图发布到控制器,您可以简单地拥有:
@model List<Path.To.Your.Models.Line>
@{
ViewBag.Title = "test";
}
<h2>test</h2>
@for (var i = 0; i < Model.Count; i++)
{
<form action=@Url.Action("ProcessLane", new { IdGroup = Model[i].IdGroup}) method="post">
<div class="row parentWrap">
@for (var j = 0; j < Model[i].RowLane.Count; j++)
{
<div class="row">
@Html.Hidden("[" + j + "].IdLane", Model[i].RowLane[j].IdLane)
@Html.Hidden("[" + j + "].LaneName", Model[i].RowLane[j].LaneName)
@Html.CheckBox("[" + j + "].IsChecked")
@Html.Label(Model[i].RowLane[j].LaneName)
</div>
}
<input type="submit" class="btn btn-primary sss" value="send" />
</div>
</form>
<hr />
}
并且,一些示例数据要在您的控制器中检查:
public ActionResult test()
{
IEnumerable<Line> line = new List<Line>
{ new Line{
IdGroup = 100,
GroupName = "Nojan",
RowLane = new List<RowLane> { new RowLane { IdLane = "1", IsChecked = true, LaneName = "pizza"},
new RowLane { IdLane = "2", IsChecked = false, LaneName = "lazogna"}
}
},
new Line{
IdGroup = 101,
GroupName = "Noj",
RowLane = new List<RowLane> { new RowLane { IdLane = "3", IsChecked = false, LaneName = "pizza"},
new RowLane { IdLane = "4", IsChecked = false, LaneName = "lazogna"}
}
}
};
return View(line.ToList());
}
public ActionResult ProcessLane(int? IdGroup, List<RowLane> input)
{
// Code here as you wish, form is submitted to this method
}
我成功地运行并测试了代码。您可以随意定制它。
希望这有帮助:)
推荐阅读
- mysql - JavaFX 如何在另一个项目中使用我自己的 .jar 库?
- c - 如何修改 BFS 算法以在给定条件下找到 2 个顶点之间的路径?
- vue.js - 添加弹出模式以 vuetify vue.js
- python - Modifying dictionary inside function without return statement
- javascript - 有没有办法检查单元格中的单词?
- python - 为什么我们将对 numpy.random.random 的调用乘以数字并减去数字?
- python - Azure 中与 Aws SqS 最相似的队列服务是什么?
- mongodb - 插入 $out 失败
- php - 如何将两个数组合并为一个php
- html - 如何从wordpress中的移动版本中删除标题栏