MVC4 input field placeholder

后端 未结 10 1232
北恋
北恋 2020-11-30 02:00

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

相关标签:
10条回答
  • 2020-11-30 02:23

    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.

    0 讨论(0)
  • 2020-11-30 02:24

    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.

    0 讨论(0)
  • 2020-11-30 02:26

    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

    0 讨论(0)
  • 2020-11-30 02:29

    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.

    0 讨论(0)
提交回复
热议问题