2012-12-27 51 views
0

我有一個get方法,我有一個名稱列表。MVC中從服務器端頁面創建單選按鈕

Public ActionResult GetlistOfNames() 
{ 
    listofPersons = SomeListOfGuys; 
    // i want to display this as a radiobutton on the clientside 
} 

我該怎麼做?

我面臨的問題是,當我嘗試這樣做,我在div下獲取文本像

<input id="name" type="radio" name="Personname"/> 

而不是實際的單選按鈕。

請幫助我一樣。

+0

你可以提供一些代表你的HTML的視圖或JS嗎?在我看來,你可能將html作爲文本插入到某個地方,你的div中放置的是正確的html,它只是不被瀏覽器渲染。 –

回答

0

您可以在關聯的視圖中爲該操作定義此項。在視圖中,您可以使用Html幫助器方法'RadioButtonFor',該方法將根據給定的列表爲您構建html。你可以找到更多細節上的具體方法on MSDN.

+0

但我無法從serverside使用RadioButtonFor。 我想從服務器端到客戶端獲取我的單選按鈕。 – vishal

+0

剃鬚刀視圖仍然在服務器端執行,唯一發送給客戶端的是生成的HTML。我想我沒有準確理解你的問題 - 你能澄清你想要完成的事情嗎? –

0

我會作一個假設在這裏,你需要渲染單選按鈕的動態生成的列表,以1由用戶選擇....

您的服務器(在Controller Action方法中,或者更好的是,在ViewModel道具/方法中)應該返回一個IEnumerable<SelectListItem>。該列表中的每個項目都將具有由您的代碼設置的「文本」和「值」屬性,某些foreach來自您的實際數據源。

我更喜歡使用'fat'ViewModels,所以所有的工作都在Model類中完成,而不是在控制器中完成。您可以創建該IEnumerable<SelectListItem>並將其放入ViewBag中,如ViewBag.NameChoices = GetSelectItemsFromDataWhatever();,就在您的控制器中。

在您看來,您可以SelectItems的列表綁定到一個ASP相當於:單選按鈕列表具有以下extention方法:

// jonlanceley.blogspot.com/2011/06/mvc3-radiobuttonlist-helper.html 
public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, 
      Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> listOfValues) 
{ 
    var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); 
     var sb = new StringBuilder(); 
     sb.Append("<span class='RadioButtonListFor'> "); 

     if (listOfValues != null) 
     { 
      // Create a radio button for each item in the list 
      foreach (SelectListItem item in listOfValues) 
       { 
        // Generate an id to be given to the radio button field 
        var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value); 

        // Create and populate a radio button using the existing html helpers 

        var htmlAttributes = new Dictionary<string, object>(); 
        htmlAttributes.Add("id", id); 

        if (item.Selected) 
         htmlAttributes.Add("checked", "checked"); 

        var radio = htmlHelper.RadioButtonFor(expression, item.Value, htmlAttributes); 


        // Create the html string that will be returned to the client 
        // e.g. <label<input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" />Line1</label> 
        sb.AppendFormat("<label>{0} {1}</label> ", radio, HttpUtility.HtmlEncode(item.Text)); 
       } 
     } 

     sb.Append(" </span>"); 
     return MvcHtmlString.Create(sb.ToString()); 
} 

並在您查看其綁定:

@Html.RadioButtonListFor(model => model.SelectedName, ViewBag.NameChoices) 

您的模型將需要一個'SelectedName'支持上述工作,它將在回發時綁定到選定的單選按鈕。