Thi*_*ijs 5 c# asp.net-mvc extension-methods razor asp.net-mvc-5
我正在使用MVC 5,我正在尝试编写一些Bootstrap扩展方法.我的目标是用'覆盖' Html.ActionLink方法Html.BootstrapLinkButton.该BootstrapLinkButton方法应生成一个"btn btn-default"自动附加的css类的链接.我的代码到目前为止:
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));
}
Run Code Online (Sandbox Code Playgroud)
这给了我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>
Run Code Online (Sandbox Code Playgroud)
我搜索了互联网,但似乎没有解决这个问题.有谁知道解决这个问题的神奇代码?
如果我的解决方案可以帮助任何人,那就是:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1918 次 |
| 最近记录: |