我对 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 为空,我在列表中有 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>
}