[c#] Display string as html in asp.net mvc view

I have a controller which generates a string containing html markup. When it displays on views, it is displayed as a simple string containing all tags.

I tried to use an Html helper to encode/decode to display it properly, but it is not working.

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

On my views,

@Html.Encode(str)

This question is related to c# asp.net asp.net-mvc asp.net-mvc-4

The answer is


I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.

I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.

So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.

I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.


you can use @Html.Raw(str)

See MSDN for more

Returns markup that is not HTML encoded.

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


You should be using IHtmlString instead:

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 need to hold HTML, I feel this is generally a better practice. First of all, it is a bit cleaner. For example:

@Html.Raw(str)

Compared to:

@str

Also, I also think it's a bit safer vs. using @Html.Raw(), as the concern of whether your data is HTML is kept in your controller. In an environment where you have front-end vs. back-end developers, your back-end developers may be more in tune with what data can hold HTML values, thus keeping this concern in the back-end (controller).

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

One other thing worth noting, is I'm not sure where you're assigning str, but a few things that concern me with how you may be implementing this.

First, this should be done in a controller, regardless of your solution (IHtmlString or Html.Raw). You should avoid any logic like this in your view, as it doesn't really belong there.

Additionally, you should be using your ViewModel for getting values to your view (and again, ideally using IHtmlString as the property type). Seeing something like @Html.Encode(str) is a little concerning, unless you were doing this just to simplify your example.


I had a similar problem with HTML input fields in MVC. The web paged only showed the first keyword of the field. Example: input field: "The quick brown fox" Displayed value: "The"

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

<input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit"
       onchange="validateInteger(this.value)" value="@ViewBag.respondingRangerUnit">

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?