ModelMetadata.Watermark and MVC View Models

送分小仙女□ 提交于 2019-12-05 11:22:48

The reason you get an empty watermark is that in your case (i.e. not using templates) ViewData actually refers to myFormModel (not myFormModel.firstFieldValue); you are essentially retrieving the watermark of your view model. Since models can't have watermarks ([Display] can't be applied to classes) ViewData.ModelMetadata.Watermark will always be empty for views.

As far as I can see, your only option here (if you don't want to use templates) is doing the watermark inline:

@Html.TextBoxFor(x => x.firstFieldValue, new { @class = "myInputStyle", placeholder = "Your watermark text here" })

By the way, if want to use templates, you need to use the templated helpers @Html.EditorFor() and @Html.DisplayFor(). @Html.TextBoxFor() is just the strongly-typed version of @Html.TextBox(). It is not templated.

I realise this is an oldie, but you can use the ModelMetadata.FromLambdaExpression() method from within your view (without using templates), i.e.

    @Html.TextBoxFor(x => x.firstFieldValue, 
        new { 
            @class = "myInputStyle", 
            @placeholder = ModelMetadata.FromLambdaExpression(x => x.firstFieldValue, ViewData).Watermark 
    })

Hope this helps someone :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!