我會作一個假設在這裏,你需要渲染單選按鈕的動態生成的列表,以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'支持上述工作,它將在回發時綁定到選定的單選按鈕。
你可以提供一些代表你的HTML的視圖或JS嗎?在我看來,你可能將html作爲文本插入到某個地方,你的div中放置的是正確的html,它只是不被瀏覽器渲染。 –