How do I create a New SelectList from a list of values and have a selected value from my database chosen. For instance a list of states, I don't want that in the database, but i want my users to chose from the list?
Thanks Paul, that would work for me in a way but I guess I should have been a bit clearer. Say I want to display the full state name and have the value be the abbreviation, any ideas on how to do that?
<% var states = new[]{
new {abbrev="Vic", full="Victoria"},
new {abbrev="NSW", full="New South Wales"},
new {abbrev="Qld", full="Queensland"}
}; %>
<%=Html.DropDownList("States",new SelectList(states, "abbrev", "full", "NSW")) %>
alivemedia
Member
43 Points
54 Posts
Drop Down List NOT from datasource
Jun 19, 2008 08:35 PM|LINK
How do I create a New SelectList from a list of values and have a selected value from my database chosen. For instance a list of states, I don't want that in the database, but i want my users to chose from the list?
MVC DropDownList
liammclennan
Member
478 Points
105 Posts
Re: Drop Down List NOT from datasource
Jun 19, 2008 09:28 PM|LINK
The data does not have to come from a database. You can use any enumerable type like a list or an array.
Eclipse Web Solutions
liam@eclipsewebsolutions.com.au
http://www.eclipsewebsolutions.com.au
Paul Linton
Star
13431 Points
2535 Posts
Re: Drop Down List NOT from datasource
Jun 19, 2008 11:07 PM|LINK
<%=Html.DropDownList("States",new SelectList(new List<string>{"NSW", "Vic", "Tas"},"Vic")) %>
alivemedia
Member
43 Points
54 Posts
Re: Drop Down List NOT from datasource
Jun 20, 2008 03:32 PM|LINK
Thanks Paul, that would work for me in a way but I guess I should have been a bit clearer. Say I want to display the full state name and have the value be the abbreviation, any ideas on how to do that?
Paul Linton
Star
13431 Points
2535 Posts
Re: Drop Down List NOT from datasource
Jun 21, 2008 04:02 AM|LINK
The easiest way is to just code the html tags
the alternative could be something like Hope that helpsAlexBecker
Member
6 Points
19 Posts
Re: Drop Down List NOT from datasource
Jun 23, 2008 02:37 PM|LINK
If you don't want to write the HTML you can do something like this
Controller:
Dictionary<string,string> states = new Dictionary<string,string>();
states.Add("NY", "New York");
states.Add("PA", "Pennsylvania");
....
ViewData["States"] = new SelectList(states, "Key", "Value", "NY");
return View("Index");
////
Page.aspx
<%= Html.DropDownList("States") %>