Populate DropDownList using MVC 4 & Entity Framework

asp.net-mvc asp.net-mvc-4 entity-framework

Question

I'm developing MVC4 & Entity Framework Application.I wanted to populate DropDownList,I wanted to bind Category List to Dodropdown list

IRepository Code

IList<Category> GetCategory();

Repository

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

    }

Controller

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

After that I stucked here.How do i bind data to Dropdownlist ?

My View Code here

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

My Controller Code

 public ActionResult AddProduct()
    {
        return View();
    }
1
8
11/9/2013 1:37:48 PM

Accepted Answer

How about using ViewBag?

View

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

Controller

public ActionResult AddProduct()
{
    ViewBag.ListOfCategories = GetCategory();
    return View();
}
6
11/9/2013 1:45:31 PM

Popular Answer

You could do this:

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

But I would recommend you to avoid ViewBag/ViewData and profit from your 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);

}

and in the view:

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

I hope I have helped



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow