开发者

Getting Html.ActionLink to generate a multi-line link

For an application i am working on, I need to have the image captions span multiple lines. Playing around I was able to get the desired effect f开发者_运维技巧rom this markup:

<a href="http://www.stackoverflow.com">Stack<br>Overflow</a>

rendered this for me:

Stack

Overflow

However I have been unable to find the right way to generate a link description for HTML.ActionLink that will render this kind of output.


If the urls is not part of your web site using an HTML helper to generate this link wouldn't bring much value. Instead simply write it as is. And if it is part of your site and you could use routing to reach the address you could write a custom HTML helper which doesn't HTML encode the link text by default:

public static class HtmlExtensions
{
    public static MvcHtmlString MyActonLink(
        this HtmlHelper html, 
        string linkText, 
        string action, 
        string controller, 
        object routeValues, 
        object htmlAttributes
    )
    {
        var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
        var url = urlHelper.Action(action, controller, routeValues);
        var anchor = new TagBuilder("a");
        anchor.InnerHtml = linkText;
        anchor.Attributes["href"] = url;
        anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        return MvcHtmlString.Create(anchor.ToString());
    }
}

and in your view:

@Html.MyActonLink(
    "Stack<br/>Overflow",    // linkText
    "MyAction",              // actionName
    "MyController",          // controllerName
    new { id = "123" },      // routeValues
    new { @class = "foo" }   // htmlAttributes
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜