Correctly making an ActionLink extension with htmlAttributes

十年热恋 提交于 2019-12-09 01:52:32

问题


I use a custom extension for my ActionLinks. I have added an attribute data_url which is meant to be translated to an attribute of data-url. This is, replacing the underscaore with a dash.

Here is link 1 using my custom extension:

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

Result: data_url

Here is link 2 using the framework ActionLink:

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

Result: data-url

Here is the extension, simple enough, except that the only way to pass the htmlAttributes through that I know of is by using the ToDictionaryR() extension. I suspect this is the problem, so I am wondering if I should be using something else. I have supplied that extension below too.

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;
}

thank you


回答1:


You could use the AnonymousObjectToHtmlAttributes method which does exactly what you want and you don't need any custom extension methods:

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)
    );
}


来源:https://stackoverflow.com/questions/9595334/correctly-making-an-actionlink-extension-with-htmlattributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!