Reputation: 87047
yeah :( simple question * blush *
Lets imagine i have the following enumeration:-
string[] languages = new string[]
{
"en (uk)", // English (colour)
"en (us)", // English (color)
"fr", // French
"es" // Spanish
};
ViewData["Languages"] = languages;
ViewData["UserLanguage"] = "en (uk)";
Armed with this, how would i display a radio button in the View? Is the only way to do this to enumerate through all the language values and render a RadioBox?
eg. pseduo-code...
<% foreach(string language in ViewData["Languages"] as string[])
{
response.write Html.RadioBox(... not sure what to set in here ...)
}%>
cheers!
Upvotes: 2
Views: 1682
Reputation: 8055
Quick and dirty:
<% foreach(string language in ViewData["Languages"] as string[]) { %>
<%= Html.RadioBox(language,language,language == ViewData["UserLanguage"].ToString()) %>
<% } %>
The problem is that you have allot of magic strings in that viewdata. What I would do is something like this:
Create a class: UserForm
class UserForm {
IList<string> _languages;
string _selectedL;
public UserForm (IList<string> languages, string selectedLanguage)
{
_languages = languages;
_selectedL = selectedLanguage;
}
IEnumerable<SelectedListItem> UserLanguages {
get {
return from l in _languages
select new SelectedListItem {
Text = l,
Value = l,
Selected = (l == _selectedL)
};
}
}
}
the view should be strongly typed and be of type : UserForm then you could render it like :
<%= Html.RadioButtonList("userLanguages",ViewData.Model.UserLanguages) %>
From the controller you would :
return View(new UserForm(listOfLanguages, selectedLanguage));
HTH.
EDIT:
OK, found it - the RadioButtonList
is an extension method in the Microsoft.Web.Mvc
namespace (the MVCFutures project) - you can get it from here : MVCFutures
Upvotes: 2