我对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中自己制作表单?
答案 0 :(得分:1)
将列表上的foreach
更改为FOR
循环,以便索引可以在lamda中使用并通过Razor视图正确呈现:
@for (int i = 0; i < Model.Users.Count(); i++) {
{
<tr>
@if(RoleUser)
{
<td class="add-td">
@Html.CheckBoxFor(modelItem => Model.Users[i].State, new { disabled = true })
</td>
<td class="disabled-label">
@Html.DisplayFor(modelItem => Model.Users[i].User)
</td>
...
...
模型绑定器然后将数据正确地绑定到列表。