我的视图中有一张表格,如下所示。列表
Model.SchoolList
有 2 条记录,并且正在按预期显示。下面是我的代码的简化版本。
模型类:
public class SchoolViewModel
{
public SchoolTableModel SchoolUser { get; set; }
}
public class SchoolTableModel
{
public List<SchoolDetails> SchoolList { get; set; }
}
public class SchoolDetails
{
public string SchoolId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
查看:
@model SchoolProj.ViewModels.SchoolViewModel
<form id = "formSchool">
<div class="table-responsive">
<table id="tblSchool" class="table table-responsive">
<thead>
<tr>
<th width="50%">Name</th>
<th width="50%">Type</th>
</tr>
</thead>
<tbody>
@if (Model != null && Model.SchoolUser.SchoolList != null && Model.SchoolUser.SchoolList.Count() > 0)
{
@for (int i = 0; i < Model.SchoolUser.SchoolList.Count; i++)
{
<tr>
<td>
<input type="hidden" asp-for= "@Model.SchoolUser.SchoolList[i].SchoolId" />
@Model.SchoolUser.SchoolList[i].Name
</td>
<td>
@Model.SchoolUser.SchoolList[i].Type
</td>
</tr>
}
}
</tbody>
</table>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" id="btnsubmit" class="btn btn-default" value="Save" />
</div>
</div>
</form>
我的控制器代码如下:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(SchoolViewModel schoolViewModel)
{
}
提交后,
schoolViewModel.SchoolUser.SchoolList
在控制器中显示为空。难道我不应该接收带有 2 个 schoolViewModel.SchoolUser.SchoolList
值的 SchoolId
因为我已经在隐藏字段中绑定了模型参数吗?
就像
SchoolId
已包含在上下文中一样,也有必要添加 Name
和 Type
:
@for (int i = 0; i < Model.SchoolUser.SchoolList.Count; i++)
{
<tr>
<td>
<input type="hidden" asp-for="@Model.SchoolUser.SchoolList[i].SchoolId" />
<input type="hidden" asp-for="@Model.SchoolUser.SchoolList[i].Name" />
@Model.SchoolUser.SchoolList[i].Name
</td>
<td>
<input type="hidden" asp-for="@Model.SchoolUser.SchoolList[i].Type" />
@Model.SchoolUser.SchoolList[i].Type
</td>
</tr>
}
<form>
标签的方法应根据操作方法定义为POST
:
<form asp-action ="Create" method="post">
@Html.AntiForgeryToken()