将枚举类型保存到数据库中将返回null mvc

时间:2015-02-06 13:02:10

标签: c# asp.net-mvc

当我尝试将dropdownList中的枚举类型保存到数据库中时,首先使用代码保存的值为null。有谁可以帮助我吗?

我的控制器:

public ActionResult Index()
{
  return View(db.Users.ToList());
}

public ActionResult Create()
{
  User model = new User();
  IEnumerable<Proov.Models.User.UserType> userTypes = Enum
    .GetValues(typeof(Proov.Models.User.UserType))
    .Cast<Proov.Models.User.UserType>();
  model.TypeList = from user in userTypes
                   select new SelectListItem
                   {
                     Text = user.ToString(),
                     Value = ((int)user).ToString()
                   };
  return View(model);
}

[HttpPost]
public ActionResult Create(User user)
{   
  if (ModelState.IsValid)
  {      
    db.Users.Add(user);
    db.SaveChanges();
    return RedirectToAction("Index");
  }
  return View(user);
}

查看

@using (Html.BeginForm())
{
  @Html.ValidationSummary(true)
  <label>Set a type for your user :</label><br />
  @Html.DropDownListFor(model=>model.UserId, Model.TypeList) 
  <p>
    <input type="submit" value="Create" />
  </p>
}

2 个答案:

答案 0 :(得分:1)

您的观看代码不正确。您将下拉列表分配给UserId而不是相应的用户类型属性。例如:

@Html.DropDownListFor(model=>model.UserTypeId, Model.TypeList) 
<p>
    <input type="submit" value="Create" />
</p>

答案 1 :(得分:0)

如果您使用ASP.NET MVC 5.1或更高版本,则可以使用:

@Html.EnumDropDownListFor(model => model.YOURENUM)