我想把一个按钮作为@ActionLink()的文本,但我做不到,因为它对我的字符串进行了HTML转义...我发现了@Html.Raw()机制,并尝试了@ActionLink().ToHtmlString(),但不知道如何将其组合在一起……
我找到了an article,它描述了为类似的目的构建一个扩展,但它太麻烦了……一定有个简单的办法吧?
发布于 2011-05-20 03:05:22
你可以写一个helper:
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>发布于 2014-09-13 18:33:56
如果您想创建一个使用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()));
}https://stackoverflow.com/questions/6063467
复制相似问题