【发布时间】:2018-02-25 18:09:48
【问题描述】:
这个问题似乎被问了很多。我浏览了在 StackOverflow 上可以找到的所有内容,据我所知,我正在做我应该做的一切,以确保视图正确地遍历列表元素并为它们创建正确的 html。但是,模型绑定不起作用。
我有这两个视图模型:
public class ProjectViewModel
{
public int ProjectId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int? StatusId { get; set; }
public IList<CoordinateViewModel> Coordinates;
}
public class CoordinateViewModel
{
public int CoordinateId { get; set; }
public double X { get; set; }
public double Y { get; set; }
}
它们在视图中是这样使用的(为便于阅读而简化):
@model ProjectViewModel
<div class="container">
<form asp-action="Edit" method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="row">
Coordinates
<table>
<thead>
<tr>
<th></th>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Coordinates.Count; i++)
{
<tr>
<td>@Html.HiddenFor(x => Model.Coordinates[i].CoordinateId)</td>
<td>@Html.TextBoxFor(x => Model.Coordinates[i].X)</td>
<td>@Html.TextBoxFor(x => Model.Coordinates[i].Y)</td>
</tr>
}
</tbody>
</table>
</div>
<div class="row">
<div class="col-md-8 form-group">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-offset-2 col-md-5">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</div>
</div>
</form>
</div>
涉及的控制器动作是这个(为了便于阅读,再次编辑):
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(ProjectViewModel viewModel)
{
return View(viewModel);
}
当表单加载时,坐标信息被填充。
提交表单时,控制器的action方法中传入的视图模型包含一个空值的坐标属性,我不知道为什么。
【问题讨论】:
标签: c# asp.net-mvc