我对 MVC 相当陌生,所以我确定我做错了什么。我正在尽我最大的努力以 MVC 的方式来完成它,而不是恢复到仅在 HTML 中手工制作它。
这是我的编辑视图
@model NotesBoard.Models.RoleViewModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>RoleViewModel</legend>
@Html.HiddenFor(model => model.Role.Name)
<div class="editor-label">
@Html.LabelFor(model => model.Role.Name)
</div>
<div class="editor-field">
@Html.DisplayFor(model => model.Role.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Role.Users)
</div>
<div class="editor-field">
<table>
<tr>
<td class="remove-td">Tick to Remove</td>
<td></td>
<td class="add-td">Tick to Add</td>
</tr>
<tr>
<td style="vertical-align:top; margin: 0px;">
<table style="margin: 0px;">
@foreach (var item in Model.Role.Users)
{
<tr>
<td class="remove-td">
@Html.CheckBoxFor(modelItem => item.State)
</td>
<td>
@Html.DisplayFor(modelItem => item.User)
</td>
</tr>
}
</table>
</td>
<td></td>
<td style="vertical-align:top; margin:0px;">
<table style="margin: 0px;">
@foreach (var item in Model.Users)
{
Boolean RoleUser = Model.Role.Users.Exists(model => model.User == item.User);
<tr>
@if(RoleUser)
{
<td class="add-td">
@Html.CheckBoxFor(modelItem => item.State, new { disabled=true })
</td>
<td class="disabled-label">
@Html.DisplayFor(modelItem => item.User)
</td>
}
else
{
<td class="add-td">
@Html.CheckBoxFor(modelItem => item.State, new { id=item.User })
</td>
<td>
@Html.DisplayFor(midelItem => item.User)
</td>
}
</tr>
}
</table>
</td>
</tr>
</table>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
这是我的模型:
public class AccountUser
{
public AccountUser() { }
public AccountUser(Int32 id, String user)
{
Id = id;
User = user;
}
[Key]
public Int32 Id { get; set; }
public String User { get; set; }
}
public class AccountUserViewModel : AccountUser
{
public AccountUserViewModel(Int32 id, String user, Boolean State = false)
{
Id = id;
User = user;
}
public Boolean State { get; set; }
}
public class RoleModel
{
public String Name { get; set; }
public List<AccountUserViewModel> Users { get; set; }
}
public class RoleViewModel
{
public RoleModel Role { get; set; }
public List<AccountUserViewModel> Users { get; set; }
}
当我从编辑视图获得回发时,两个用户列表都是空的。
到目前为止,这是我的控制器中的 Post 方法:
[HttpPost]
[Authorize(Roles = "Admin")]
public ActionResult Edit(RoleViewModel model)
{
if (ModelState.IsValid)
{
var data = Request.Form;
return RedirectToAction("Index");
}
return View(model);
}
如果我尝试使用 Request.form 集合直接提取数据,则复选框都命名为“item.state”。我应该如何实现此视图以获取下降数据,而无需恢复到基本上只是自己在平面旧 HTML 中制作表单?