I am using ASP.NET MVC 2 (.NET 3.5), and need to manually define what shall be an Options list. When I do so I get a drop down menu, with each of the manual entries reading 'System.Web.Mvc.SelectListItem'.
My view model defines the list as such:
public SelectList YesNoList
{
get
{
List<SelectListItem> tmpList = new List<SelectListItem>();
tmpList.Add(new SelectListItem {Text = "", Value = ""});
tmpList.Add(new SelectListItem {Text = "Yes", Value = "1"});
tmpList.Add(new SelectListItem {Text = "No", Value = "0"});
YesNoList = new SelectList(tmpList,"");
}
private set{}
}
In the view I reference this using the the Html.DropDownList:
Html.DropDownList("FieldName", viewmodel.YesNoList);
What I am expecting to be rendered on the final web page should be like:
<select id="FieldName" name="FieldName">
<option value=""/>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
Instead I get:
<select id="FieldName" name="FieldName">
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
</select>
I am at a loss, as I cannot figure out why the type is being returned so would appreciate it if anybody could point out to me what is wrong with the viewmodel definition, or point out a better way. I was hesitant to derive the SelectList from collections of C# classes as the SelectList would provide a consistant way to iterate through the values and display text.
Thanks in advance, hopefully somebody can help.
Cheers,
J
A dropdown can handle a List<SelectListItem>
too, just send that in stead.
Html.DropDownList("FieldName", viewmodel.YesNoList);
and
public List<SelectListItem> YesNoList
{
get
{
List<SelectListItem> YesNoList = new List<SelectListItem>();
YesNoList.Add(new SelectListItem {Text = "", Value = ""});
YesNoList.Add(new SelectListItem {Text = "Yes", Value = "1"});
YesNoList.Add(new SelectListItem {Text = "No", Value = "0"});
return YesNoList;
}
private set{}
}
you are actually doing it wrong on making the selectlist.
it should be:
new SelectList(tmpList, "Value", "Text");
and then forget my above code. you can do this with any List, if you give it the list and the value and text "key"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With