nick gowdy
nick gowdy

Reputation: 6501

Using DropDownListFor with model

On my view I am using a list as my model and each list item is of type model, so it looks like this:

@model IEnumerable<UserManager.Models.vw_UserManager_Model>

and I am trying to loop through this list and add a specific property to a DropDownListFor:

@for (int i = 0; i < Model.Count(); i++)
{
    Html.DropDownListFor(model => model.ElementAt(i).module, new SelectList(Model, Model.ElementAt(i).module));
}

But when I do this it doesn't render a dropdownmenu on my page.

Image of my list in locals

Can someone help?

Upvotes: 1

Views: 624

Answers (1)

Levi Botelho
Levi Botelho

Reputation: 25204

You can't render a dropdown list for a model because there is no way of representing the model in its entirety in a dropdown. What is ASP.NET supposed to render?

What you can do if you would like to select a model from a list is to run a LINQ Select query on the list, whereby you create an IEnumerable<SelectListItem> like this:

var selectList = Model
    .Select(x => new SelectListItem
    {
        Name = x.module_name,
        Value = x.module
    });

I have tried to take the values from the screenshot that you posted. Apologies if I made an error. You get the idea...

What this code does is loop through the collection of your object type (Model.Select) and returns a collection of SelectListItem. If you are unfamiliar with LINQ you need to think of Select as a transformative function. It takes a collection, and for each element transforms it into something else and returns the result. Here, it takes each element of the Model collection and creates a SelectListItem. It then returns an IEnumerable<SelectListItem>.

To render the list on the page you do the following:

@Html.DropDownListFor(Model.MyValue, selectList)

...where Model.MyValue is the variable which receives the selected value (assuming that the value, model is a string, which it appears to be).

Upvotes: 2

Related Questions