【发布时间】:2019-07-02 22:22:58
【问题描述】:
我正在尝试将模型从视图传递回控制器。我将 NaborViewModel 传递给 View。它是一个对象列表,每个对象都有 4 个复选框(其中一些是随机选中的)。
型号:
public class NaborViewModel
{
public List<WowClass> WowClasses { get; set; }
}
动作:
[HttpGet]
public ActionResult Nabor()
{
NaborViewModel viewModel = new NaborViewModel();
DatabaseDataContext context = new DatabaseDataContext();
viewModel.WowClasses = context.WowClasses.ToList();
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Nabor(NaborViewModel model)
{
//DB actions
return RedirectToAction(Consts.ActionNabor);
}
在视图中,我有 2 个表格,每个表格都有不同的方法。第一个是我创建的,认为它可能会起作用。 第二种形式是我在网上找到的方法。 第一个是正确显示传递的数据(填充复选框)。第二个甚至显示未选中的每个复选框。 提交表单时,它们都将 null 返回给控制器操作。
查看:
@using (Html.BeginForm(Consts.ActionNabor, Consts.ControllerAdmin, FormMethod.Post))
{
@Html.AntiForgeryToken()
<table class="admin-table">
<thead>
<tr>
<th>Class</th>
<th>Status</th>
<th colspan="3">Požadované talenty</th>
</tr>
</thead>
<tbody>
@foreach (var cls in Model.WowClasses)
{
<tr>
@Html.HiddenFor(x => cls.Id)
<td>@cls.ClassName</td>
<td>@Html.CheckBoxFor(x => cls.Open)</td>
<td style="text-align: left">@Html.CheckBoxFor(x => cls.NeedTalents1) <span>@cls.Talents1</span></td>
<td style="text-align: left">@Html.CheckBoxFor(x => cls.NeedTalents2) <span>@cls.Talents2</span></td>
<td style="text-align: left">@Html.CheckBoxFor(x => cls.NeedTalents3) <span>@cls.Talents3</span></td>
</tr>
}
</tbody>
</table>
<input type="submit" value="@Consts.Submit" />
}
<div class="horizontal-line-both"></div>
@using (Html.BeginForm(Consts.ActionNabor, Consts.ControllerAdmin, FormMethod.Post))
{
@Html.AntiForgeryToken()
<table class="admin-table">
<thead>
<tr>
<th>Class</th>
<th>Status</th>
<th colspan="3">Požadované talenty</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.WowClasses.Count; i++)
{
<tr>
<td>
<input type="text" value="@Model.WowClasses[i].ClassName" name="Expense[@i].Id">
</td>
<td>
<input type="checkbox" value="@Model.WowClasses[i].Open" name="Expense[@i].Id">
</td>
<td>
<input type="checkbox" value="@Model.WowClasses[i].NeedTalents1" name="Expense[@i].Id">
</td>
<td>
<input type="checkbox" value="@Model.WowClasses[i].NeedTalents2" name="Expense[@i].Id">
</td>
<td>
<input type="checkbox" value="@Model.WowClasses[i].NeedTalents3" name="Expense[@i].Id">
</td>
<td>
<input type="hidden" value="@i" name="Expense[@i].Id">
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="@Consts.Submit" />
}
【问题讨论】:
标签: c# asp.net asp.net-mvc model-view-controller