如何在MVC4和EF中将列表框值保存到数据库中?

时间:2015-03-09 15:24:19

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我有一个注册表单,允许管理员为特定用户选择菜单项。

我的目标是将选定的菜单项以逗号分隔的值保存到数据库中。

问题是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>

1 个答案:

答案 0 :(得分:2)

如果我正确理解了这个问题,您应该执行以下操作:

[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");
}

假设您的菜单项正确发布,而没有看到视图很难分辨。