使用MVC 4& Pop填充DropDownList。实体框架

时间:2013-11-09 13:37:48

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

我正在开发MVC4&实体框架Application.I想要填充DropDownList,我想将Category List绑定到Dodropdown列表

IRepository Code

IList<Category> GetCategory();

存储库

public IList<Category> GetCategory()
    {
        return (from c in context.Categories
                select c).ToList();

    }

控制器

  public IList<Category> GetCategory()
    {
        return icategoryRepository.GetCategory();
    }

之后我一直坚持到这里。我如何将数据绑定到Dropdownlist?

我在这里查看代码

<label for="ProductType">Product Type</label>
       @Html.DropDownListFor(m => m.ProductType,new List<SelectListItem>)

我的控制器代码

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

4 个答案:

答案 0 :(得分:6)

如何使用ViewBag?

查看

<label for="ProductType">Product Type</label>
   @Html.DropDownListFor(m => m.ProductType,ViewBag.ListOfCategories)

控制器

public ActionResult AddProduct()
{
    ViewBag.ListOfCategories = GetCategory();
    return View();
}

答案 1 :(得分:5)

你可以这样做:

@Html.DropDownListFor(x => x.IdCategory, ViewBag.Categories)

但我建议你避免使用ViewBag / ViewData并从你的viewmodel中获利:

public ActionResult AddProduct()
{
    var model = new TestModel();

//This is just a example, but I advise you to turn your IList in a SelectListItem, for view is more easy to work. Your List Categories will be like this hardcoded:

model.ListCategories= new SelectList(new[]
{
    new { Value = "1", Text = "Category 1" },
    new { Value = "2", Text = "Category 2" },
    new { Value = "3", Text = "Category 3" },
}, "Value", "Text");

return View(model);

}

并在视图中:

@Html.DropDownListFor(x => x.IdCategory, Model.ListCategories)

我希望我有所帮助

答案 2 :(得分:2)

使用ViewBag(正如其他人在其他答案/评论中建议的那样)从控制器获取数据以查看通常被视为代码气味。

理想情况下,ViewModel应包含视图所需的所有数据。因此,使用您的控制器在ViewModel的属性上填充此数据:

SelectList ProductTypes { get; set; }

然后将您的下拉列表绑定到此值

@Html.DropDownListFor(m => m.ProductType, Model.ProductTypes)

您可以在this post上找到相同的答案。

答案 3 :(得分:0)

非常简单的Code一步一步 1)在实体框架类

var productsList = (from product in dbContext.Products
                     select new ProductDTO
                     {
                       ProductId = product.ProductId,
                       ProductName = product.ProductName,
                       }).ToList();

2)在控制器中

ViewBag.productsList = new EntityFrameWorkClass().GetBusinessSubCategoriesListForDD();

3)在视图中

@Html.DropDownList("Product_ProductId", new SelectList(ViewBag.productsList , "ProductId", "ProductName"), new { @class = "form-control" })

OR

@Html.DropDownListFor(m=>m.Product_ProductId, new SelectList(ViewBag.productsList , "ProductId", "ProductName"), new { @class = "form-control" })