Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Raw ActionLink linkText

I want to put a button as the text of an @ActionLink() but I can't because it HTML-escapes my string... I found the @Html.Raw() mechanism and have tried the @ActionLink().ToHtmlString() but can't figure out how to put it together...

I found an article that describes building an extension for a similar purpose but it's eeky to go to that much trouble... there must be an easy way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could write a 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());
    }
}

and then use this helper:

@Html.MyActionLink(
    "<span>Hello World</span>", 
    "foo", 
    "home",
    new { id = "123" },
    new { @class = "foo" }
)

which given default routes would produce:

<a class="foo" href="/home/foo/123"><span>Hello World</span></a>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...