我遇到的问题是虽然AssignedUsers属性在我的构造函数中初始化(在离开GET Edit之前),但在提交表单后,它在POST Edit操作中返回为null。所有其他财产保持其状态。
除了在ModelState.IsValid检查之后(以及在返回View之前)重新初始化属性之外,还有其他方法可以解决这个问题吗?
型号:
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);
}
答案 0 :(得分:2)
您不是在表单中发布数据。所以它不会被返回到编辑方法。您应该采用哪种方式,我不建议将数据发布到您的表单。
我会做这样的改变
型号:
public class GroupModel {
public List<int> AssignedUserIds { get; set; }
MultiSelectList _assignedUsers;
public MultiSelectList AssignedUsers () {
return _assignedUsers ?? _assignedUsers = new MultiSelectList(
AllUserGroups
.Where(userGroup => userGroup.GroupId == Id)
.Select(userGroup => userGroup.Users)
.ToList(),
"Id",
"Username");
}
private object _allUserGroups; /* not sure what this is */
private object AllUserGroups {
get { return _allUserGroups ?? _allUserGroups = AccountManagementAdapter.GetUserGroups();
}
public GroupModel(Groups group) {
AssignedUserIds = AllUserGroups
.Where(userGroup => userGroup.GroupId == Id)
.Select(userGroup => userGroup.UserId)
.ToList();
}
查看:
@Html.ListBoxFor(group => group.AssignedUserIds, Model.AssignedUsers())
或你可以这样做
public class GroupModel {
public List<int> AssignedUserIds { get; set; }
public MultiSelectList AssignedUsers { get; set; }
private object allUserGroups
public GroupModel() {
allUserGroups = AccountManagementAdapter.GetUserGroups();
AssignedUsers = new MultiSelectList(
allUserGroups
.Where(userGroup => userGroup.GroupId == Id)
.Select(userGroup => userGroup.Users)
.ToList(),
"Id",
"Username");
}
public GroupModel(Groups group) :this() {
AssignedUserIds = allUserGroups
.Where(userGroup => userGroup.GroupId == Id)
.Select(userGroup => userGroup.UserId)
.ToList();
}