codecompleting
codecompleting

Reputation: 9611

MVC helper for a dropdown list that uses a List<Cars>

I have a List collection in my strongly typed viewdata.

How do I use the Html.DropDownList helper?

<%= Html.DropDownList(ViewData.Model.Cars) %>

(the above doesn't work, doesn't seem to match any of the signatures)

This is MVC2.

Upvotes: 1

Views: 638

Answers (1)

Craig
Craig

Reputation: 7076

If your Car class looked something like this

public class Car
{
    public int Id { get; set; }

    public string Name { get; set; }
}

And you put a property on your view model like this

public int CarId { get; set; }

Your resulting view model would look like this

public class YourViewModel
{
    public int CarId { get; set; }

    public List<Car> Cars { get; set; }
}

You could do this

this.Html.DropDownListFor(x => x.CarId, new SelectList(this.Model.Cars, "Id", "Name"))

When posted, CarId would get get bound to the bound by the default model binder if the view model was a parameter to the Action.

Upvotes: 6

Related Questions