Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 input field placeholder

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"> 
like image 978
Tomas Avatar asked Apr 16 '13 07:04

Tomas


People also ask

How do I use TextBoxFor in HTML?

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.

What is TextBox and TextBoxFor in MVC?

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.


1 Answers

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.

like image 174
von v. Avatar answered Sep 28 '22 02:09

von v.