Michael S
Michael S

Reputation: 4740

HTML in MVC RouteLink

I have a RouteLink constructed like so

<p class="articleLink">
    @MvcHelper.Html.RouteLink(article.Title, "Article_Route", new RouteValueDictionary() { { "articleId", article.Id }, { "seoUrl", article.SeoUrl } }))
</p>

However, article.Title could potentially contain HTML i.e. the value could be <em>Sample</em> Title which in turn gets rendered like so

<a href="/Article/111111/Sample-Title">&lt;em&gt;Sample&lt;/em&gt; Title</a>

Is there any way to prevent the HTML from being escaped, and instead to be treated as actual HTML? Or do I need to create a standard HTML <a href... link in this case (thus losing all the niceties associated with the RouteLink helper).

Upvotes: 4

Views: 3523

Answers (2)

Ben
Ben

Reputation: 282

You can use HtmlHelper.Raw(). Having said that, it is probably not a good idea to keep any HTML in your model/view model, which is against the principle of separation of model and presentation, also a security hazard.

Upvotes: -1

nemesv
nemesv

Reputation: 139798

If you want HTML inside your anchor don't use the Html.RouteLink (because it will HTML encode the link text by default as you noticed) instead of build your a tag by hand with using Url.RouteUrl to generate the url:

<p class="articleLink">
    <a href="@(Url.RouteUrl("Article_Route",
                   new RouteValueDictionary() 
                      { { "articleId", article.Id }, 
                        { "seoUrl", article.SeoUrl } }))">
        @Html.Raw(article.Title)
    </a>
</p>

Or you can create your own non encoding RouteLink helper.

Upvotes: 7

Related Questions