我遇到的问题是,尽管在我的构造函数中初始化了 AssignedUsers 属性(在离开 GET 编辑之前),但在提交表单后,它在 POST 编辑操作中返回为 null。所有其他属性保持其状态。
除了在 ModelState.IsValid 检查之后(以及在返回视图之前)重新初始化属性之外,还有其他方法可以解决这个问题吗?
模型:
public class GroupModel {
public List<int> AssignedUserIds { get; set; }
public MultiSelectList AssignedUsers { get; set; }
public GroupModel(Groups group) {
var allUserGroups = AccountManagementAdapter.GetUserGroups();
AssignedUsers = new MultiSelectList(
allUserGroups
.Where(userGroup => userGroup.GroupId == Id)
.Select(userGroup => userGroup.Users)
.ToList(),
"Id",
"Username");
AssignedUserIds = allUserGroups
.Where(userGroup => userGroup.GroupId == Id)
.Select(userGroup => userGroup.UserId)
.ToList();
}
看法:
@using (Html.BeginForm()) {
@Html.ListBoxFor(group => group.AssignedUserIds, Model.AssignedUsers)
<input type="submit" value="Save"/>
}
控制器:
[HttpGet]
public ActionResult Edit(int id) {
GroupModel groupModel = new GroupModel(AccountManagementAdapter.GetGroups().FirstOrDefault(group => group.Id == id));
return View(groupModel);
}
[HttpPost]
public ActionResult Edit(GroupModel group) {
if (ModelState.IsValid) {
group = new GroupModel(AccountManagementAdapter.UpdateUsersForGroup(group.Id, group.AssignedUserIds));
ViewBag.Success = true;
}
return View(group);
}