我对MVC有一些问题,我将尝试描述。我的模型中有2个课程。
public class ApplicationPermissionVM
{
public ApplicationPermission Permission { get; set; }
public bool IsSelected { get; set; }
}
public class RoleAndPermissonsModel
{
//Constructor skipped
public ApplicationRole ApplicationRole { get; set; }
public IEnumerable<ApplicationPermissionVM> Permissions { get; set; }
}
第二个模型是主模型,我在控制器中初始化模型。 ApplicationRole为null,我在列表中有19个元素。当我发布表单时,将创建ApplicationRole成员,但权限列表将为空,因此将丢失所有选择。如果有人知道是什么问题请写信给我。 控制器:
[HttpGet]
public ActionResult NewRole()
{
_model = new RoleAndPermissonsModel();
return View(_model);
}
[HttpPost]
public ActionResult NewRole(RoleAndPermissonsModel newRole)
{
if (ModelState.IsValid)
{
var id = _applicationRoleService.AddNewRole(newRole.ApplicationRole);
_applicationRoleService.AssignPermissionsToRole(newRole.SelectedItems, id);
}
return RedirectToAction("Index");
}
查看:
@model EO.Core.WebUI.Models.RoleAndPermissonsModel
@using (Html.BeginForm("NewRole", "PermissionRole", FormMethod.Post, new { id = "frmNewRole" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>ApplicationRole</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ApplicationRole.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ApplicationRole.Name)
@Html.ValidationMessageFor(model => model.ApplicationRole.Name)
</div>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.IsSelected)
</th>
<th></th>
</tr>
@foreach (var item in Model.Permissions)
{
<tr>
<td>
@Html.EditorFor(modelItem => item.IsSelected)
</td>
<td>
@Html.DisplayFor(modelItem => item.Permission.Name);
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
答案 0 :(得分:1)
您需要手动循环遍历列表并将其输出为
<input type="text"
id="Permissions[0].IsSelected"
name="Permissions[0].IsSelected" value="" />
所以,将代码更改为:
@for(int i = 0; i < Model.Permissions.Count; i++)
{
<tr>
<td><input type="checkbox"
id="Permissions[@(i)].IsSelected"
name="Permissions[@(i)].IsSelected" /></td>
<td><input type="text"
id="Permissions[@(i)].Permission.Name"
name="Permissions[@(i)].Permission.Name" /></td>
</tr>
}
因为您的类型Permissions
中有一个对象,所以请记住初始化它,否则您将得到一个空引用。
public class RoleAndPermissonsModel
{
public RoleAndPermissonsModel() {
this.Permissions = new List<ApplicationPermissionVM>();
}
public ApplicationRole ApplicationRole { get; set; }
public IEnumerable<ApplicationPermissionVM> Permissions { get; set; }
}
或者您可以轻松创建ViewModel
,并使用它将您的模型与视图互连。
注意:我很想知道,如果您的列表始终为null(因为您传递的是空/空列表),为什么要循环遍历Model.Permissions
?
为了进行“编辑”视图,循环代码应为:
@for(int i = 0; i < Model.Permissions.Count; i++)
{
<tr>
<td><input type="checkbox"
@(Permissions[i].IsSelected ? "checked='checked'" : "")
id="Permissions[@(i)].IsSelected"
name="Permissions[@(i)].IsSelected" /></td>
<td><input type="text"
id="Permissions[@(i)].Permission.Name"
name="Permissions[@(i)].Permission.Name"
value="@(Permissions[i].Permission.Name)" /></td>
</tr>
}
如果已选中该复选框,则需要添加checked
,并将权限名称填入其他输入。