Raw ActionLink linkText

时间:2011-05-19 18:50:08

标签: asp.net-mvc-3 razor html-helper actionlink

我想把一个按钮作为@ActionLink()的文本,但我不能,因为它HTML转义我的字符串......我找到了@Html.Raw()机制,并尝试了{{1但是无法弄清楚如何把它放在一起......

我发现an article描述了为类似目的而构建扩展程序,但是为了解决这个问题真是太过分了......必须有一个简单的方法吗?

2 个答案:

答案 0 :(得分:13)

你可以写一个帮手:

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>

答案 1 :(得分:1)

如果要创建使用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()));
    }