views:

560

answers:

1

Hi folks,

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!

+2  A: 

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 :

  1. create a class : UserForm

    class UserForm{
    
    
     IList<string> _languages;
     string _selectedL;
    
    
     ctor(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 )};
       }
     }
    
    
    }
    
  2. the view should be strongly typed and be of type : UserForm then you could render it like :

    <%=Html.RadioButtonList("userLanguages",ViewData.Model.UserLanguages) %>

  3. 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

sirrocco
AFAIK, Html.RadioButtonList doesn't exist anymore ... can u confirm?
Pure.Krome
Well , I haven't yet switched to the RTM , so you are probably correct :| . I wonder what the reason was.
sirrocco
+1 for the otherwise very good design.
Adrian Grigore