【问题标题】:Getting a dropdown list to work with codefirst 4.1 MVC3获取下拉列表以使用 codefirst 4.1 MVC3
【发布时间】:2011-09-03 19:16:29
【问题描述】:

我试图了解 MVC3 的实体框架 4.1 codefirst 方法。

我正在尝试将下拉列表添加到创建视图中,但运气不佳。

我有一个看起来像的模型

public class BusinessModel
{
    public int Id { get; set; }

    [Required]
    public string BusinessName { get; set; }
    [Required]
    public string PhoneNumber { get; set; }


    public int BusinessTypeId { get; set; }
    public virtual BusinessTypeModel BuinessTypeModel { get; set; }

}

public class BusinessTypeModel
{
    public int Id { get; set; }
    public string BusinessType { get; set; }
}

我的下拉列表看起来像

     @Html.DropDownListFor(model => model.BusinessTypeId,
         ((IEnumerable<CRM.Models.BusinessTypeModel>)ViewBag.BuinessTypes)
    .Select(option => new SelectListItem
    {

        Text = (option == null ? "None" : option.BusinessType),

        Value = option.Id.ToString(),

        Selected = (Model != null) && (option.Id == Model.BusinessTypeId)

    }), "Select Business Type...")

我还没有用我的控制器做任何事情,所以它是香草

 public ActionResult Create()
    {
        return View();
    } 

但是我得到一个空错误

值不能为空。 参数名称:来源

现在我假设这是空的,因为我没有正确绑定下拉列表但是我不确定我哪里出错了。

有人可以帮忙解决我做错了什么吗?

【问题讨论】:

    标签: entity-framework asp.net-mvc-3 ef-code-first


    【解决方案1】:

    您在视图中使用“ViewBag.BuinessTypes”,

    也许您应该在 Create Controller 中分配 ViewBag.BuinessTypes 的值?

    喜欢:

     public ActionResult Create()
        {
            ViewBag.BuinessTypes = ...;        
            return View();
        }
    

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      相关资源
      最近更新 更多