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)
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With