niki b
niki b

Reputation: 989

Render string to html in MVC

A similar question was already asked here but the answer did not solve my problem below.

How can I render a string to html? Basically, I need to pass a string to the view that has an "a" tag definition in it. What I want is to render it as an actual html link that is clickable.

View Model (simplified):

public class MyViewModel
{
    public string MyLink { get; set; }
}

In Controller (simplified):

public IActionResult Index()
{
    MyViewModel model = new MyViewModel();

    model.MyLink = "<a href="http://www.google.com">http://www.google.com</a>"

    return View(model);
}

In View (at first line):

@model MyNamespace.ViewModel.MyViewModel

Then below, these html markups (1st lines after the numbers) displays the results (2nd lines). But none of them are actual links that you can click on.

1
@Model.MyLink
<a href="http://www.google.com">http://www.google.com</a>

2
<pre>@Html.Raw(@Model.MyLink)</pre>
<a href="http://www.google.com">http://www.google.com</a>

3
@Html.Encode(@Html.Raw(@Model.MyLink))
&amp;lt;a href=&amp;quot;http://www.google.com&amp;quot;&amp;gt;http://www.google.com&amp;lt;/a&amp;gt;

4 
@Html.Encode(@Model.MyLink)
result same as #3.

Any help will be appreciated. Thanks in advance.

Upvotes: 8

Views: 15688

Answers (1)

nurdyguy
nurdyguy

Reputation: 2945

In the controller use

model.MyLink = HttpUtility.HtmlDecode(url);

then in the view use

@Html.Raw(Model.MyLink)

The first converts it to use

Upvotes: 16

Related Questions