Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 715
niki b Avatar asked Jun 01 '16 20:06

niki b


1 Answers

In the controller use

model.MyLink = HttpUtility.HtmlDecode(url);

then in the view use

@Html.Raw(Model.MyLink)

The first converts it to use

like image 96
nurdyguy Avatar answered Oct 07 '22 23:10

nurdyguy