2012-03-07 90 views
1

我爲我的動作鏈接使用自定義擴展。我添加了一個屬性data_url,這意味着要翻譯爲屬性data-url。這是用短劃線替換下劃線。正確使用htmlAttributes製作ActionLink擴展

下面是鏈接1使用我的自定義擴展:

@Ajax.ActionLink("Add", MyRoutes.GetAdd(), new AjaxOptions() 
    , new { data_url = Url.Action(...)}) 

結果:data_url

這裏是鏈接2使用框架的ActionLink:

@Ajax.ActionLink("Add 2", "x", "x", null, new AjaxOptions() 
    , new { data_url = Url.Action(...) }) 

結果:data-url

這是擴展,很簡單,除了通過我知道的唯一方法來傳遞htmlAttributes是通過使用ToDictionaryR()擴展。我懷疑這是問題,所以我想知道如果我應該使用別的東西。我也提供了下面的擴展。

public static MvcHtmlString ActionLink(this AjaxHelper helper, string linkText 
     , RouteValueDictionary routeValues, AjaxOptions ajaxOptions 
     , object htmlAttributes = null) 
{ 
    return helper.ActionLink(linkText, routeValues["Action"].ToString() 
     , routeValues["Controller"].ToString(), routeValues, ajaxOptions 
     , (htmlAttributes == null ? null : htmlAttributes.ToDictionaryR())); 
} 

public static IDictionary<string, object> ToDictionaryR(this object obj) 
{ 
    return TurnObjectIntoDictionary(obj); 
} 
public static IDictionary<string, object> TurnObjectIntoDictionary(object data) 
{ 
    var attr = BindingFlags.Public | BindingFlags.Instance; 
    var dict = new Dictionary<string, object>(); 
    foreach (var property in data.GetType().GetProperties(attr)) 
    { 
     if (property.CanRead) 
     { 
      dict.Add(property.Name, property.GetValue(data, null)); 
     } 
    } 
    return dict; 
} 

謝謝

+0

你可以這樣做:'VAR DIC = new RouteValueDictionary(data)'。儘管它不是真正的RVD。它仍然有效。 – RPM1984 2012-03-07 05:15:44

+0

感謝您的建議,因爲它很好,很短。我希望它能解決我的問題,但沒有。 – 2012-03-07 05:18:16

回答

3

你可以使用你想要做這正是AnonymousObjectToHtmlAttributes方法,你不需要任何自定義擴展方法:

public static MvcHtmlString ActionLink(
    this AjaxHelper helper, 
    string linkText, 
    RouteValueDictionary routeValues, 
    AjaxOptions ajaxOptions, 
    object htmlAttributes = null 
) 
{ 
    return helper.ActionLink(
     linkText,  
     routeValues["Action"].ToString(), 
     routeValues["Controller"].ToString(), 
     routeValues, 
     ajaxOptions, 
     htmlAttributes == null ? null : HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) 
    ); 
} 
+0

令人驚歎。謝謝! – 2012-03-07 07:35:16