我使用的是 MVC 5,我正在尝试编写一些 Bootstrap 扩展方法。我的目标是用 Html.BootstrapLinkButton
“覆盖”Html.ActionLink
方法。 BootstrapLinkButton
方法应该生成一个带有 css 类 "btn btn-default"
自动附加的链接。
到目前为止我的代码:
public static MvcHtmlString BootstrapLinkButton(this HtmlHelper htmlHelper,
string linkText,string actionName, string controllerName,
object routeValues = null, object htmlAttributes = null)
{
var attributes =
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (attributes.ContainsKey("class"))
{
object value;
attributes.TryGetValue("class", out value);
value = (value as string) + " btn btn-default";
attributes["class"] = value;
}
else
{
attributes["class"] = "btn btn-default";
}
return htmlHelper.ActionLink(
linkText, actionName, controllerName, routeValues,
new Dictionary<string, object>(attributes));
}
这在 HTML 中给出了以下结果:
<a comparer="System.Collections.Generic.GenericEqualityComparer`1[System.String]"
count="3"
keys="System.Collections.Generic.Dictionary`2
+KeyCollection[System.String,System.Object]"
values="System.Collections.Generic.Dictionary`2
+ValueCollection[System.String,System.Object]"
href="/test/test/">
Test
</a>
我在网上搜索过,但似乎没有什么可以解决这个问题。有谁知道解决这个问题的神奇代码?
最佳答案
如果我的解决方案可以帮助任何人,那就是:
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));
}
}
关于c# - 扩展方法中的 HtmlAttributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20083883/