这是我的实现,便于重复使用
辅助方法扩展类
namespace Extensions {
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class HtmlExtensions {
public static MvcHtmlString FALink(this HtmlHelper htmlHelper, string action, string controller, string link_text, string fa_class, string btn_css_classes = "", string button_id = "", object route_values = null) {
// declare the span
TagBuilder span = new TagBuilder("span");
span.AddCssClass($"fa fa-{fa_class}");
span.MergeAttribute("aria-hidden", "true");
// declare the anchor tag
TagBuilder anchor = new TagBuilder("a");
// Add the href attribute to the <a> element
if (string.IsNullOrEmpty(controller) || string.IsNullOrEmpty(action))
anchor.MergeAttribute("href", "#");
else
anchor.MergeAttribute("href", new UrlHelper(HttpContext.Current.Request.RequestContext).Action(action, controller, route_values));
// Add the <span> element and the text to the <a> element
anchor.InnerHtml = $"{span} {link_text}";
anchor.AddCssClass(btn_css_classes);
anchor.GenerateId(button_id);
// Create the helper
return MvcHtmlString.Create(anchor.ToString(TagRenderMode.Normal));
}
}
}
确保在 View 中包含命名空间,以便方法可用
Razor View 中的示例用法
您可以像使用任何股票 @Html 助手一样使用逗号分隔值来传递您想要的任何路由值
使用所有参数:
@Html.FALink("ActionNameHere", "ControllerNameHere", "Back to List", "th-list", "btn btn-info", "btn_back_to_list", new {area="AreaNameHere"})
基本链接类型按钮:
@Html.FALink("ActionNameHere", "ControllerNameHere", "Back to List, "th-list")
使用引导程序为文本着色的基本链接类型按钮
@Html.FALink("ActionNameHere", "ControllerNameHere", "Back to List", "th-list, "btn-info")
- 当我使用 Font Awesome 时,您可以轻松地将 fa 替换为 bootstrap glyphicon 类以使用 bootstrap glyphicons
- 如果没有传入控制器或动作,它使用#作为链接位置,这样它就可以很好地与下拉交互