HtmlAttributes in Extension Method

折月煮酒 提交于 2019-12-05 11:17:26

If my solution could help anyone, here it is:

    public static MvcHtmlString BootstrapLinkButton(this HtmlHelper htmlHelper, 
        string linkText, 
        string actionName, 
        string controllerName = null, 
        object routeValues = null, 
        object htmlAttributes = null,
        string btnStyle = "default")
    {
        var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        controllerName = 
            controllerName ?? 
            HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

        if (attributes.ContainsKey("class"))
        {
            object value;
            attributes.TryGetValue("class", out value);
            value = string.Format("{0} btn btn-{1}", (value as string), btnStyle);
            attributes["class"] = value;
        }
        else
        {
            attributes["class"] = string.Format("btn btn-{0}", btnStyle);
        }

        return htmlHelper.ActionLink(
            linkText, 
            actionName, 
            controllerName, 
            new RouteValueDictionary(routeValues), 
            new Dictionary<string, object>(attributes));
    }
}

It's already implemented in TwitterBootstrapMVC

Here is some relevant code

Most likely the reason your code is failing is because htmlHelper.ActionLink(...) method there is confused about which overload needs to be used. There is no overload on it that takes string, string, object, Dictionary, which is what you are trying to pass to it.

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