2013-01-14 32 views
0

我現在正在使用this code來實現使用MVC4的RadioButtonList。如何在此HtmlHelper中添加htmlAttributes?

而你可以看到,該函數沒有htmlAttributes參數。所以我想補充一下,這就是問題所在。請檢查RadioButtonFor()的htmlAttributes是否被id佔用。

我試圖添加它,但引發錯誤,因爲該ID已存在的循環。

public static class HtmlExtensions 
{ 
    public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
     this HtmlHelper<TModel> htmlHelper, 
     Expression<Func<TModel, TProperty>> expression, 
     IEnumerable<SelectListItem> listOfValues) 
    { 
     return htmlHelper.RadioButtonForSelectList(expression, listOfValues, null); 
    } 

    public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
     this HtmlHelper<TModel> htmlHelper, 
     Expression<Func<TModel, TProperty>> expression, 
     IEnumerable<SelectListItem> listOfValues, 
     object htmlAttributes) 
    { 
     return htmlHelper.RadioButtonForSelectList(expression, listOfValues, new RouteValueDictionary(htmlAttributes)); 
    } 

    public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
     this HtmlHelper<TModel> htmlHelper, 
     Expression<Func<TModel, TProperty>> expression, 
     IEnumerable<SelectListItem> listOfValues, 
     IDictionary<string, object> htmlAttributes) 
    { 
     var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); 
     var sb = new StringBuilder(); 
     if (listOfValues != null) 
     { 
      foreach (SelectListItem item in listOfValues) 
      { 
       var id = string.Format(
        "{0}_{1}", 
        metaData.PropertyName, 
        item.Value 
       ); 

       var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString(); 
       sb.AppendFormat(
        "{0}<label for=\"{1}\">{2}</label>", 
        radio, 
        id, 
        HttpUtility.HtmlEncode(item.Text) 
       ); 
      } 
     } 
     return MvcHtmlString.Create(sb.ToString()); 
    } 
} 

回答

1

在第三種方法中,它看起來像傳遞給正在創建的放射按鈕的html屬性是new { id = id }。嘗試用方法中的參數替換它。

修訂

在HTML屬性ID並在每個循環迭代分配一個新的值來標識。

if (listOfValues != null) 
{ 
    if (!htmlAttributes.ContainsKey("id")) 
    { 
     htmlAttributes.Add("id", null); 
    } 
    foreach (SelectListItem item in listOfValues) 
    { 
     var id = string.Format(
      "{0}_{1}", 
      metaData.PropertyName, 
      item.Value 
     ); 
     htmlAttributes["id"] = id; 
     var radio = htmlHelper.RadioButtonFor(expression, item.Value, htmlAttributes).ToHtmlString(); 
     sb.AppendFormat(
      "{0}<label for=\"{1}\">{2}</label>", 
      radio, 
      id, 
      HttpUtility.HtmlEncode(item.Text) 
     ); 
    } 
} 
+0

是的,但刪除了id = id,我需要該參數..沒有辦法加入他們嗎? –

+0

關閉我的頭頂,可以手動添加它們,如:htmlAttributes.Add(「id」,id)。 –

+0

我正在使用循環內..我需要克隆字典我想這樣做 –

相關問題