II创建了一个动态表单,允许用户向表中添加行,其中包含用于输入的输入。
我想将字段数组绑定到操作中的模型。
我相信我已按照正确的命名程序进行任何其他行" fieldName [0]"
我创建了一个条目并发布到了操作但绑定没有发生
我检查了请求的标题,可以看到发布的信息
这里是表单数据:
CompanyAllId[0]: 0
EmployeeId[0]: 0
Name[0]: Test Name
Position[0]: Manager
MonthlyEarnings[0]: 10000
startDate[0]: 02/04/2018 17:58:00
EmploymentType[0]: Full Time
这是我的观点
<form asp-action="SaveEmployee">
<table class="table table-bordered table-hover table-striped" id="employee-table">
<thead>
<tr>
<th>
Name
</th>
<th>
Position
</th>
<th>
Monthly Earnings
</th>
<th>
Start Date
</th>
<th>
Employment Type
</th>
</thead>
<tbody class="table-body">
@for (int i = 0; i < Model.Count; i++)
{
<tr class="table-row" data-id="0">
@Html.Hidden("CompanyAllId[" + i + "]", Model[i].CompanyAllId)
@Html.Hidden("EmployeeId[" + i + "]", Model[i].EmployeeId)
<td> @Html.TextBox("Name[" + i + "]", Model[i].Name)</td>
<td>@Html.TextBox("Position[" + i + "]", Model[i].Position)</td>
<td>@Html.TextBox("MonthlyEarnings[" + i + "]", Model[i].MonthlyEarnings)</td>
<td>@Html.TextBox("startDate[" + i + "]", Model[i].startDate)</td>
<td>@Html.TextBox("EmploymentType[" + i + "]", Model[i].EmploymentType)</td>
</tr>
}
</tbody>
</table>
<button class="clone-button btn btn-flat btn-primary">Add Row</button>
<button type="submit" class="btn btn-flat btn-primary">Save</button>
</form>
控制器操作
[HttpPost]
[Authorize]
public async Task<IActionResult> SaveEmployee(List<Models.CompanyViewModels.Employees.Employee> vm)
{
return View();
}
答案 0 :(得分:1)
我相信我已遵循正确的命名
不,你没有。您必须为元素提供索引,而不是属性
因此,如果您的参数名为vm
:
@Html.Hidden("vm[" + i + "].CompanyAllId", Model[i].CompanyAllId)
@Html.Hidden("vm[" + i + "].EmployeeId", Model[i].EmployeeId)
<td> @Html.TextBox("vm[" + i + "].Name", Model[i].Name)</td>
<td>@Html.TextBox("vm[" + i + "].Position", Model[i].Position)</td>
<td>@Html.TextBox("vm[" + i + "].MonthlyEarnings", Model[i].MonthlyEarnings)</td>
<td>@Html.TextBox("vm[" + i + "].startDate", Model[i].startDate)</td>
<td>@Html.TextBox("vm[" + i + "].EmploymentType", Model[i].EmploymentType)</td>
所以,你应该最终得到像......
vm[0].CompanyAllId: 0
vm[0].EmployeeId: 0
vm[0].Name: Test Name
vm[0].Position: Manager
vm[0].MonthlyEarnings: 10000
vm[0].startDate: 02/04/2018 17:58:00
vm[0].EmploymentType: Full Time