我创建了一个ParentModel,因为我想在其中使用两个模型,以便我可以在MVC中使用相同的视图。
当我获得初始加载数据时,父模型中定义的两个属性都会正确填充。 但是,当我尝试添加新数据时,我将第二个属性视为null。 这是我的代码:
public class UserModel
{
public User User { get; set; }
public IEnumerable<RolesModel> rolesModel { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Add(UserModel userDetails)
{
try
{
if (ModelState.IsValid)
{
userDetails.User.FullName = userDetails.User.FirstName + " " + userDetails.User.MiddleName + " " + userDetails.User.LastName;
userDetails.User.CreatedDate = DateTime.Now;
_userService.Insert(userDetails.User);
_unitOfWorkAsync.SaveChanges();
foreach (RolesModel rolesModel in userDetails.rolesModel)
{
// Here userdetails.rolesmodel is null
}
}
查看:
@model Axp.Gcst.Gps.Web.Areas.Admin.Models.UserModel
@using (Html.BeginForm("Add", "user", FormMethod.Post, new { @class = "form-horizontal" }))
{
@Html.AntiForgeryToken()
@Html.Partial("_UserDetails", Model)
@foreach (var itemRole in Model.rolesModel)
{
if (itemRole.Role.RoleGroupId == item.RoleGroupId)
{
<div class="col-md-12 col-sm-12 col-xs-12 panel_cell">
@Html.CheckBoxFor(model => itemRole.isSelected, new { @class = "panel_checkbox" })
@Html.DisplayFor(model => itemRole.Role.Name)
</div>
@Html.HiddenFor(model=>itemRole.Role.RoleId)
}
}
}
答案 0 :(得分:1)
当您回发List Back to controller时,您应该使用for循环:
@foreach (var itemRole in Model.rolesModel)
{
if (itemRole.Role.RoleGroupId == item.RoleGroupId)
{
@Html.CheckBoxFor(model => itemRole.isSelected, new { @class = "panel_checkbox" })
@Html.DisplayFor(model => itemRole.Role.Name)
@Html.HiddenFor(model => itemRole.Role.RoleId)
}
}
使用For循环:
@for(int i =0; i< Model.rolesModel.Count; i++){
@Html.CheckBoxFor(m => m.rolesModel[i].isSelected, new { @class = "panel_checkbox" })
@Html.DisplayFor(m => m.rolesModel[i].Role.Name)
@Html.HiddenFor(m => m.rolesModel[i].Role.RoleId)
}
这里有一个类似的答案:https://stackoverflow.com/a/27926181/1910735
MVC Model Binder要求输入字段采用以下格式:
list[0].prop1
list[0].prop2
list[0].prop3
list[1].prop1
list[1].prop2
list[1].prop3