Reputation: 17384
My model is:
public string Vehicle
public DropDownListModel()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "one", Value = "one" });
items.Add(new SelectListItem() { Text = "two", Value = "two" });
SelectList items2 = new SelectList(items);
VehicleList = items2;
}
public string Vehicle
{
get;
set;
}
public SelectList VehicleList
{
get;
set;
}
}
I am want to render selectList into a dropdwonlist but what I am getting is
My View is this:
@using ( Html.BeginForm("Post","Guestbook"))
{
@Html.Label("Name") @Html.DropDownListFor(m=> m.Vehicle,Model.VehicleList)<br />
<input type="submit" name="submit" value="submit" />
}
What am I doing wrong. I have spend quite a bit of time on this and checked various SO question but could not resolve this.
Upvotes: 1
Views: 159
Reputation: 5549
You might want to edit the code to make it more clear what you're doing... but it's fairly obvious: the code works exactly as intended, but you're actually using it wrong.
SelectList isn't meant to be created using a list of existing SelectListItems. You should feed it a collection of your own items, specifying what properties on those items are meant for the value and name of the corresponding HTML elements that will be generated. The code works (sort of) because you're presented with the actual SelectListItems that you're creating. You can simply stick them in a List or other IEnumerable and it'll also work. But don't combine the two approaches.
Here's a working example, given the model class:
public class Vehicle
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Model
{
public int SelectedId { get; set; }
public IEnumerable<Vehicle> Items { get; set; }
}
the following Razor code works:
@Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.Items, "Id", "Name"))
Upvotes: 0
Reputation: 18175
Agree with Max that VehicleList isn't being initialized. Even if you set it to the list it still doesn't know what property is the value and what is the data. Try changing your model like so:
public class DropDownListModel
{
public DropDownListModel()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add( new SelectListItem() { Text = "one", Value = "one" } );
items.Add( new SelectListItem() { Text = "two", Value = "two" } );
VehicleList = new SelectList( items, "Value", "Text" );
}
public string Vehicle { get; set; }
public SelectList VehicleList { get; set; }
}
Upvotes: 2
Reputation: 860
Where is your VehicleList
is being initialized?
It doesn't look like DropDownListModel
is being called and even if it was - what is items2
that it sets?
try setting this.VehicleList
in there instead.
Upvotes: 2