Asp.net-Mvc

使用 MVC 4 和實體框架填充 DropDownList

  • January 16, 2017

我正在開發 MVC4 和實體框架應用程序。我想填充 DropDownList,我想將類別列表綁定到 Dodropdown 列表

IRepository 程式碼

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();
   }

使用 ViewBag 怎麼樣?

看法

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

控制器

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

你可以這樣做:

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

但我建議您避免使用 ViewBag/ViewData 並從您的視圖模型中獲利:

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)

我希望我有幫助

引用自:https://stackoverflow.com/questions/19876604