DropDownList From Objects MVC
Asked Answered
E

1

6

Ok so I want make a DropDownList from my object list here is my getting object method

public List<Category> GetCategoriesList()
{
    BaseShopEntities context = new BaseShopEntities();
    List<Category> uniqCategories = (from c in context.Category
                                             select c).Distinct().ToList<Category>();

    return uniqCategories;
}

I was trying to put it into the ViewBag like this:

ViewBag.Categories = proxy.GetCategoriesList().ToList();

If im taking only names of Categorys and parsing it to string there is no problem but I need ID too

I Want get data like this but don't know how

@Html.DropDownList("CategoryID", new SelectList(ViewBag.Categories.Name));
Euphony answered 19/5, 2013 at 15:44 Comment(0)
S
6

Firstly, GetCategoriesList already returns a List, so you don't need ToList when you add it to the ViewBag:

ViewBag.Categories = proxy.GetCategoriesList();

Secondly, in order to create a DropDownList that has independent names and values, you need the following overload of the SelectList constructor:

SelectList(IEnumerable, String, String)

Here, you specify the list with which to populate the SelectList as well as two strings, where the first is the name of the value field of the elements in the list and the second is the name of the text field. The values of these fields are then retrieved using reflection. In your case, it'll probably look something like this:

@Html.DropDownList("CategoryID",
    new SelectList(ViewBag.Categories, "Id", "Name"));

Here, I am assuming that each category has an Id field and a Name field. If these field names aren't correct, you'll need to change the strings passed into the SelectList constructor accordingly.

On a side note: You should create a separate view model for categories that is separate from your database entity class and create a list of these instead. Your views shouldn't be accessing your data entities directly.

Sedulity answered 19/5, 2013 at 20:32 Comment(1)
Saved my hours. Worked like a charmFatidic

© 2022 - 2024 — McMap. All rights reserved.