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 Prompt = "E-Mail" is not passed to ViewData.ModelMetadata.Watermark while generating control. Why?
Model
public class LogOnModel { [Required] [Display(Name = "E-Mail", Prompt = "E-Mail")] [DataType(DataType.EmailAddress)] public string Email { get; set; } } @Html.TextBoxFor(m => m.Email, new { placeholder = ViewData.ModelMetadata.Watermark }) I get html code where placeholder tag do not has any text
<input data-val="true" data-val-regex="Please enter a valid e-mail address" data-val-required="The E-Mail field is required." id="Email" name="Email" placeholder="" type="text" value="" class="valid">
The HtmlHelper class includes two extension methods TextBox() and TextBoxFor<TModel, TProperty>() that renders the HTML textbox control <input type="text"> in the razor view. It is recommended to use the generic TextBoxFor<TModel, TProperty>() method, which is less error prons and performs fast.
IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view. You can do the same things with both, but you should use typed views and TextboxFor when possible.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With