Display string as html in asp.net mvc view
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">
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.
You are close you want to use @Html.Raw(str)
@Html.Encode
takes strings and ensures that all the special characters are handled properly. These include characters like spaces.
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.