我有一个注册表,允许管理员为特定用户选择菜单项。
我的目的是将所选菜单项作为逗号分隔的值保存到数据库中。
问题在于MENU
,无论更新模型如何,始终将的值设置为null。
User.cs
public partial class User
{
public User()
{
this.Mobilizations = new HashSet<Mobilization>();
}
...
public string ADDRESS { get; set; }
public string PHONE { get; set; }
public string MENU { get; set; }
}
UserViewModel.cs
public class userViewModel
{
public User User { get; set; }
public SelectList MenuList { get; set; }
[Required(ErrorMessage="Select some menu items")]
public string[] MenuIds { get; set; }
}
Controller.cs
[HttpPost]
public ActionResult Create(userViewModel model)
{
var menuIds = string.Join(",", model.MenuIds);
var user = new User()
{
MENU=menuIds
};
TryUpdateModel(model);
if (ModelState.IsValid) //<= The value of MENU not getting updated
{
_db.Entry(model.User).State = EntityState.Modified;
_db.SaveChanges();
}
return RedirectToAction("Create");
}
看法
<div class="form-group">
@Html.Label("Menu", new { @class = "col-sm-2 control-label " })
<div class="col-sm-10 ">
@Html.ListBoxFor(model=>model.MenuIds,Model.MenuList,new {id="menuListBox", @class = "chosen-select",multiple="multiple",
style="width:350px"})
@Html.ValidationMessageFor(model =>model.MenuIds)
</div>
</div>
如果我正确理解了该问题,则应该执行以下操作:
[HttpPost]
public ActionResult Create(userViewModel model)
{
TryUpdateModel(model);
if (ModelState.IsValid) //<= The value of MENU not getting updated
{
model.User.MENU = string.Join(",", model.MenuIds);
_db.Entry(model.User).State = EntityState.Modified;
_db.SaveChanges();
}
return RedirectToAction("Create");
}
假设您的菜单项正确发布,而看不到“视图”,则很难分辨。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句