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">
This question is related to
asp.net-mvc
asp.net-mvc-4
There are such of ways to Bind a Placeholder to View:
1) With use of MVC Data Annotations:
Model:
[Required]
[Display(Prompt = "Enter Your First Name")]
public string FirstName { get; set; }
Razor Syntax:
@Html.TextBoxFor(m => m.FirstName, new { placeholder = @Html.DisplayNameFor(n => n.UserName)})
2) With use of MVC Data Annotations But with DisplayName:
Model:
[Required]
[DisplayName("Enter Your First Name")]
public string FirstName { get; set; }
Razor Syntax:
@Html.TextBoxFor(m => m.FirstName, new { placeholder = @Html.DisplayNameFor(n => n.UserName)})
3) Without use of MVC Data Annotation (recommended):
Razor Syntax:
@Html.TextBoxFor(m => m.FirstName, new { @placeholder = "Enter Your First Name")
I did so
Field in model:
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
Razor:
<li>
@Html.TextBoxFor(m => m.UserName, new { placeholder = Html.DisplayNameFor(n => n.UserName)})
</li>
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
Try this:
@Html.TextbBoxFor(x=>x.Email,new { @[email protected]}
If this possible or else what could be the way
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.
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.
Of course it does:
@Html.TextBoxFor(x => x.Email, new { @placeholder = "Email" })
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control",@placeholder = "Name" })
This works:
@Html.TextBox("name", null, new { placeholder = "Text" })
Source: Stackoverflow.com