Reputation: 837
I am trying to enter bold tags in the following statement but they are not rendering properly.
@(user.AlternateId.Count() > 1 ? id.Value + "<b> ( </b>" + id.Key.Substring(0,3) + "<b> ) </b>" : id.Value)
Help is much appreciated!
Upvotes: 0
Views: 871
Reputation: 239250
For string values, Razor automatically HTML encodes any HTML. To counter this, you need to convert the string to IHtmlString
. The easiest way to do that is to just wrap the return in Html.Raw
:
@Html.Raw(user.AlternateId.Count() > 1 ? id.Value + "<b> ( </b>" + id.Key.Substring(0,3) + "<b> ) </b>" : id.Value)
Alternatively, you can simply create an instance of MvcHtmlString
(which implements IHtmlString
):
@(new MvcHtmlString(user.AlternateId.Count() > 1 ? id.Value + "<b> ( </b>" + id.Key.Substring(0,3) + "<b> ) </b>" : id.Value))
For your specific use case, here, Html.Raw
is more intuitive, but in other scenarios (such as HtmlHelper
extensions) it can be helpful to know that you can just return an instance of MvcHtmlString
.
Upvotes: 1
Reputation: 218722
This should work.
@if user.AlternateId.Any())
{
@id.Value <b>(</b> @id.Key.Substring(0,3) <b>)</b>
}
else
{
@id.Value
}
I am hoping that your id.Key
will always have a length of 3+ chars ,otherwise the call to SubString
is going to give you an exception. If you are not sure about that ,you might consider writing a custom Substring method (an extension method) which check the string length before trying to do the SubString operation as explained in this post.
Upvotes: 2