How to put html entity in Asp.net mvc Html helper EditorFor placeholder

279 views Asked by At

If i use raw html <input /> with placeholder like:

<input id="TextSearch" name="TextSearch" placeholder="&#xf002;" type="text" value="" style="font-family: 'FontAwesome'" />

it renders like: enter image description here that is fine. But if i use Asp.net mvc Html helper like:

@Html.EditorFor(m => m.TextSearch, new { placeholder = "&#xf002;", style="font-family: 'FontAwesome';" })

it renders like: enter image description here it can't render FontAwesome icon. It treats as string.

How can i render it correctly using Html helper @Html.EditorFor() ?

2

There are 2 answers

0
Vish On BEST ANSWER

You need to used HttpUtility.HtmlDecode for this, so your HTMLHelper should be like below,

@Html.EditorFor(m => m.TextSearch, new { htmlAttributes = new { @PlaceHolder = HttpUtility.HtmlDecode("&#xf002;"), @Style = "font-family: 'FontAwesome'" } })
1
Tetsuya Yamamoto On

You're passing the placeholder and style HTML attributes as additionalViewData, not htmlAttributes (see EditorFor with 2 overloads here). A simple TextBoxFor with HttpUtility.HtmlDecode() should work for all MVC versions:

@Html.TextBoxFor(m => m.TextSearch, new { @placeholder = HttpUtility.HtmlDecode("&#xf002;"), @style = "font-family: 'FontAwesome'" })

Take note that usage of htmlAttributes inside EditorFor only works for MVC 5.1 and above. If you're using MVC version 5.1+, you should use this EditorFor setting, otherwise use TextBoxFor helper as mentioned above:

@Html.EditorFor(m => m.TextSearch, new { htmlAttributes = new { @placeholder = HttpUtility.HtmlDecode("&#xf002;"), @style = "font-family: 'FontAwesome'" }})

See this fiddle to see the difference of both helpers.