Is there a way to write the Html5 placeholder using @Html.EditorFor, or should I just use the TextBoxFor extension i.e.
@Html.TextBoxFor(model => model.Title, new { @placeholder = "Enter title here"})
Or would it make sense to write our own custom extension that can maybe use the 'Description' display attribute via DataAnnotations (similar to this)?
Of course, then the same question applies to 'autofocus' as well.
I use this way with Resource file (don't need Prompt anymore !)
You may take a look at the following article for writing a custom
DataAnnotationsModelMetadataProvider
.And here's another, more ASP.NET MVC 3ish way to proceed involving the newly introduced IMetadataAware interface.
Start by creating a custom attribute implementing this interface:
And then decorate your model with it:
Next define a controller:
A corresponding view:
And finally the editor template (
~/Views/Shared/EditorTemplates/string.cshtml
):I think create a custom EditorTemplate is not good solution, beause you need to care about many possible tepmlates for different cases: strings, numsers, comboboxes and so on. Other solution is custom extention to HtmlHelper.
Model:
Html helper extension:
}
A corresponding view:
As smnbss comments in Darin Dimitrov's answer,
Prompt
exists for exactly this purpose, so there is no need to create a custom attribute. From the the documentation:To use it, just decorate your view model's property like so:
This text is then conveniently placed in
ModelMetadata.Watermark
. Out of the box, the default template in MVC 3 ignores theWatermark
property, but making it work is really simple. All you need to do is tweaking the default string template, to tell MVC how to render it. Just edit String.cshtml, like Darin does, except that rather than getting the watermark fromModelMetadata.AdditionalValues
, you get it straight fromModelMetadata.Watermark
:~/Views/Shared/EditorTemplates/String.cshtml:
And that is it.
As you can see, the key to make everything work is the
placeholder = ViewData.ModelMetadata.Watermark
bit.If you also want to enable watermarking for multi-line textboxes (textareas), you do the same for MultilineText.cshtml:
~/Views/Shared/EditorTemplates/MultilineText.cshtml:
Here is a solution I made using the above ideas that can be used for TextBoxFor and PasswordFor: