0

It seems like this seemingly simple task has never been done before.

I have a controller with an action that retrieves my table cultures that contain my language info:

    [HandleError]
    [ChildActionOnly]
    public ActionResult LanguageDropdownlist()
    {
        var languageDropdownlist = _unitOfWork.CulturesRepository.Get();
        return PartialView("_LanguageSelectionPartial", languageDropdownlist.ToList());
    }

languageDropdownlist is structured as follows:

List languageDropdownlistItems 
[0]
    - display_name
    - id
    - name
    - ...
[1]
    - display_name
    - id
    - name
    - ...
[2]
    - display_name
    - id
    - name
    - ...
[3]
    - display_name
    - id
    - name
    - ...

I pass a list to the view.

In the view do the following:

@model List<ArtWebShop.Models.cultures>


<p>
    @Html.DropDownList("name", (IEnumerable<SelectListItem>)Model)
</p>

How for the love of God do I populate the dropdownlist, the above code that is located in the view obviously doesn't work, but I can't seem to find a single explanation with code from the controller and the view.

P.S.: I do not wish to use viewData or viewBag.

tereško
  • 58,060
  • 25
  • 98
  • 150
reaper_unique
  • 2,916
  • 3
  • 28
  • 48

2 Answers2

0

Look on: How do you create a dropdownlist from an enum in ASP.NET MVC?

I like that <%: Html.EnumDropDownListFor(model => model.MyEnumProperty) %>

Did work for you?

Community
  • 1
  • 1
  • Nop that's not it, but I think I have it. I pass my IEnumerable object when I create a selectList instance, var culturelist = _unitOfWork.CulturesRepository.Get(); var languageList = new SelectList(culturelist); Then pass that SelectList to my view using return PartialView("_LanguageSelectionPartial", languageList); The only problem now, is that the list is one level to big, so it shows the types of [0], [1],... instead of the languages. so I need a linq statement that retrieves only the id and name of my cultures and puts them in a list. – reaper_unique Dec 06 '12 at 17:13
0

I've found my solution. Got my inspiration from: http://forums.asp.net/t/1817879.aspx/1 It's actually pretty simple.

In my Controller:

    public ActionResult LanguageDropdownlist()
    {
        var culturelist = (_unitOfWork.CulturesRepository.Get()).ToArray();
        var list = new List<SelectListItem>();
                    for (int i = 0; i < culturelist.Count(); i++)
        {
            list.Add(new SelectListItem { Text = culturelist[i].name, Value = culturelist[i].id.ToString() });
        }

        return PartialView("_LanguageSelectionPartial", list);

    }

Here I Add them to my view so that I can access them there.

And finally in my Partial view:

@model List<SelectListItem>


<p> 
    @Html.DropDownList("language-dropdown",  Model)
</p>

I access them through @model and put them in @Html.DropDownList.

reaper_unique
  • 2,916
  • 3
  • 28
  • 48