How do I add placeholder text from the model into a MVC view?

后端 未结 9 996
余生分开走
余生分开走 2021-02-05 12:43

I have a model:

[DataType(DataType.EmailAddress)]
[DisplayFormat(ConvertEmptyStringToNull = true)]
[Display(Prompt = \"Email Address\")]
public string Email { ge         


        
相关标签:
9条回答
  • 2021-02-05 13:27

    The correct solution to get the Prompt value instead of the DisplayName in a non-templated control context is the following:

    @Html.EditorFor(model => model.Email, 
        new { @class = "form-control input-md",
        placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark
    })
    

    This will also - unlike the accepted solution using @Html.DisplayNameFor(m=>m.Email) - not double-escape the watermark text, which depending on the text and the language displayed can be a problem.

    0 讨论(0)
  • 2021-02-05 13:27

    Use TextBoxFor:

    @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @placeholder = Html.DisplayNameFor(m => m.Email) })
    
    0 讨论(0)
  • 2021-02-05 13:29

    Use TextBoxFor like so:

     @Html.TextBoxFor(model => model.LastName, new{placeholder="Last Name"})
    
    0 讨论(0)
提交回复
热议问题