Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?
Implementing placeholders in Razor can be easily performed by swapping EditorFor
for TextBoxFor
. Just remember to add a placeholder
attribute:
This line of code generates an input box with placeholder text, immediately connecting to your model's Property.
Placeholder Text with ModelMetadata
If you're eying a more MVC-centric approach, consider using ModelMetadata. Add a [Display(Prompt = "Fill in your text here")]
decoration to your ViewModel properties, essentially commanding MVC to do the heavy lifting:
Then in Views/Shared/EditorTemplates/String.cshtml
, customize your string template with a neat line of ViewData.ModelMetadata.Watermark
:
After setting this up, @Html.EditorFor(m => m.Name)
honors the placeholder text you defined in your model.
Crafting Custom HtmlHelper Extensions
When placeholders are your bread and butter and you're more inclined towards stickiness with EditorFor
, take the custom route by writing an HtmlHelper extension method:
Execute it as you would a standard EditorFor
:
Reacting Dynamically with Placeholders
Sometimes, placeholders need to have the ability to adapt to runtime changes. Use ViewData
to assign the placeholder text right when your view is generated:
In your controller action, activate this feature by setting ViewData
:
Placeholders with Multilingual Support
To accomplish multilingual support for your placeholders, apply Resource files and meld them with DisplayAttribute
:
Configure your DataAnnotationsModelMetadataProvider
for this function to play well with resource files.
Autofocusing First Input
Improve user experience by enabling autofocus on the first input box. Build a fresh HtmlHelper extension
for autofocus
:
To auto-focus on a certain field at the beginning, code it like so:
Rickrolling with MVC Templates
Go nuclear by modifying the MVC default templates to include the placeholder
attribute. This isn't for the faint-hearted, but once done, each time you use EditorFor
for strings, it'll pick up the behavior coded into the template:
Get this snippet placed in your Views/Shared/EditorTemplates/String.cshtml
file, and watch the magic happen.
Was this article helpful?