我想放一个按钮作为@ActionLink()
的文本,但我不能,因为它 HTML 转义了我的字符串......我找到了@Html.Raw()
机制并尝试了@ActionLink().ToHtmlString()
但不知道如何将其组合在一起......
我找到了一篇文章,描述了为类似目的构建扩展,但去那么麻烦是令人讨厌的......一定有一个简单的方法吗?
你可以写一个助手:
public static class HtmlExtensions
{
public static IHtmlString MyActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller,
object routeValues,
object htmlAttributes
)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var anchor = new TagBuilder("a");
anchor.InnerHtml = linkText;
anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return MvcHtmlString.Create(anchor.ToString());
}
}
然后使用此帮助程序:
@Html.MyActionLink(
"<span>Hello World</span>",
"foo",
"home",
new { id = "123" },
new { @class = "foo" }
)
给定默认路由将产生:
<a class="foo" href="/home/foo/123"><span>Hello World</span></a>
如果要
创建使用 T4MVC 库的自定义操作链接,可以编写以下代码:
public static System.Web.IHtmlString DtxActionLink(
this System.Web.Mvc.HtmlHelper html, string linkText,
System.Web.Mvc.ActionResult actionResult = null,
object htmlAttributes = null)
{
System.Web.Mvc.IT4MVCActionResult oT4MVCActionResult =
actionResult as System.Web.Mvc.IT4MVCActionResult;
if (oT4MVCActionResult == null)
{
return (null);
}
System.Web.Mvc.UrlHelper oUrlHelper =
new System.Web.Mvc.UrlHelper(html.ViewContext.RequestContext);
System.Web.Mvc.TagBuilder oTagBuilder =
new System.Web.Mvc.TagBuilder("a");
oTagBuilder.InnerHtml = linkText;
oTagBuilder.AddCssClass("btn btn-default");
oTagBuilder.Attributes["href"] = oUrlHelper.Action
(oT4MVCActionResult.Action,
oT4MVCActionResult.Controller,
oT4MVCActionResult.RouteValueDictionary);
oTagBuilder.MergeAttributes
(new System.Web.Routing.RouteValueDictionary(htmlAttributes));
return (html.Raw(oTagBuilder.ToString()));
}