Display string as html in asp.net mvc view

I have a controller that generates a string containing html markups.Now, when I show it in the views, it displays as a simple string containing all the tags. I tried to use the Html helper for encoding / decoding to display it correctly, but it does not work.

string str= "<a href="/Home/Profile/seeker">seeker</a> has applied to <a href="/Jobs/Details/9">Job</a> floated by you.</br>"; 

In my mind

 @Html.Encode(str) 
+58
c # asp.net-mvc asp.net-mvc-4
Nov 14 '13 at 14:45
source share
4 answers

You are close, you want to use @Html.Raw(str)

@Html.Encode takes strings and ensures that all special characters are correctly processed. These include characters such as spaces.

+101
Nov 14 '13 at 14:48
source share

Instead, you should use IHtmlString :

 IHtmlString str = new HtmlString("<a href="/Home/Profile/seeker">seeker</a> has applied to <a href="/Jobs/Details/9">Job</a> floated by you.</br>"); 

Whenever you have model properties or variables that must contain HTML, I find that this is usually a better practice. First of all, it's a little cleaner. For example:

 @Html.Raw(str) 

Compared with:

 @str 

In addition, I also think this is a little safer than using @Html.Raw() , since the problem is whether your data is stored in HTML in your controller. In an environment where you have front-end and third-party developers, your third-party developers may be more accurately what data may contain HTML values, thereby saving this problem in the background (controller).

I usually try to avoid using Html.Raw() whenever possible.

Another thing worth noting, I'm not sure where you assign str , but a few things that concern me with how you can implement this.

Firstly, this should be done in the controller, regardless of your solution ( IHtmlString or Html.Raw ). You should avoid logic like this, in your opinion, since it does not really belong.

In addition, you should use the ViewModel to get the values โ€‹โ€‹in your view (and again, ideally using IHtmlString as the property type). Seeing something like @Html.Encode(str) bit relative if you are not doing this just to simplify your example.

+20
Nov 14 '13 at 14:51
source share

you can use @Html.Raw(str)

See MSDN for more.

Returns markup not encoded in HTML.

This method wraps HTML markup using the IHtmlString class, which displays unencoded HTML.

+6
Nov 14 '13 at 14:50
source share

I had a similar problem with HTML input fields in MVC. The web page shows only the first field keyword. Example: input field: "Fast brown fox" Display value: "The"

The resolution was to put the variable in quotation marks in the value statement as follows:

 <input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit" onchange="validateInteger(this.value)" value="@ViewBag.respondingRangerUnit"> 
0
Jan 05 '16 at 13:08 on
source share



All Articles