具有代码优先模型的MVC DropDown列表

时间:2011-05-08 14:17:54

标签: asp.net-mvc asp.net-mvc-3 razor

我有几个基本型号,一个用于产品,一个用于类别。 如何在模型中关联这两者,以便在添加新产品时,我可以从DropDownList中选择产品所属的类别?

我正在使用ASP.NET MVC 3 - 使用工具更新和带有HTML 5标记的Razor语法。

我一直试图让这项工作没有运气,有人可以指出我正确的方向。

3 个答案:

答案 0 :(得分:1)

我得到了它的工作......刚刚和Scott Hansselmen一起观看了Mix 11 Keynote。

工作代码......

 public class Product
 {
    public int Id { get; set; }
    public string Name { get; set; }      
    public string Description { get; set; }

    public int CategoryId { get; set; }
    public Category Category { get; set; }
 }

 public class Category
 {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Product> Products { get; set; }
 }

现在,在创建控制器时,MVC将为产品创建页面上的类别生成下拉列表。因此,您也可以选择产品所属的类别。

答案 1 :(得分:1)

假设您有两个这样的表(及其相关类):

<强>产品

  • 的ProductID
  • 类别ID
  • 产品名称
  • ....

<强>分类

  • 类别ID
  • 类别名称
  • ...

为Helper创建一个新类,然后添加IEnumerable类型的方法&lt; SelectListItem&gt;以(值,文本)格式返回类别列表:

public class ListHelper
    {
        public static IEnumerable<SelectListItem> GetCategoryList()
        {
            using (SiteDataContext db = new SiteDataContext())
            {
                var list = from l in db.Categories()
                           orderby l.CategoryName
                           select new SelectListItem { Value = l.CategoryID.ToString(), Text = l.CategoryName };

                return list.ToList();
            }
        }
    }

在您的视图中,添加一个组合框以使用此方法:

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Category</legend>
        <div class="editor-label">
            Select a category:
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.CategoryID, Helpers.ListHelper.GetCategoryList())
        </div>
    </fieldset>
    <fieldset>
        <legend>Product</legend>

        <div class="editor-label">
            Product Name:
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductName)
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>

        ...

    </fieldset>
    <p>
        <input type="submit" value="Create" />
    </p>
}

然后在你的帖子Action中获取Product对象并将其保存到数据库:

        [HttpPost]
        public ActionResult Add(Product product)
        {
            if (ModelState.IsValid)
            {
                productService.InsertProduct(product);
                productService.Save();
                ...
            }
            else
            {
                return View(product);
            }
        }

答案 2 :(得分:0)

Product实体需要具有Category属性,然后您可以创建包含所有类别的下拉列表,并选择所选产品的Category。

我知道网站上有这方面的例子,但你可以在谷歌的帮助下轻松找到一个例子。

相关问题