Does MVC4
by default support placeholders
for generated input fields? I didn\'t found anything so I am trying to implement my own but unfortunately
By default, it does not. However, you can use the MVCHtml5Toolkit NuGet package that has HTML helpers that can output HTML5. For your example, after installing the toolkit you can then use the following HTML helper call:
@Html.Html5TextBoxFor(m => m.Email, InputTypes.InputType.Email)
This will output the following HTML:
<input id="Email" name="Email" placeholder="E-Mail" type="Email" value="">
As can be seen, the placeholder is now correctly rendered.
An alternative to using a plugin is using an editor template. What you need to do is to create a template file in Shared\EditorTemplates
folder and call it String.cshtml
. Then put this in that file:
@Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue,
new { placeholder = ViewData.ModelMetadata.Watermark })
Then use it in your view like this:
@Html.EditorFor(m=>Model.UnitPercent)
The downside, this works for properties of type string
, and you will have to create a template for each type
that you want support for a watermark.
You can easily add Css class, placeholder , etc. as shown below:
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", placeholder="Name" })
Hope this helps
The correct solution to get the Prompt
value in a non-templated control context is:
@Html.TextBoxFor(model => model.Email,
new { placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark }
)
This will also not double-escape the watermark text.