在CSHTML中为input元素添加了占位符文本

时间:2017-04-19 13:15:00

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

我目前正在编写ASP.Net MVC应用程序

我已经成功地在CSHTML中创建了一个输入框。

@Html.EditorFor(model => model.Test, new { htmlAttributes = new { @class = "form-control"} })

我现在想从控制器中获取字符串的内容,并添加为占位符文本。我尝试了以下

@Html.EditorFor(model => model.Test, new { htmlAttributes = new { @class = "form-control", placeholder = @Html.DisplayFor(model => model.Test) } })

但是这样设置了占位符:placeholder="" 如果我改为使用@Html.DisplayNameFor,则会将占位符设置为变量的名称Test,但我想要实际的字符串内容。我知道可以使用Viewbag将文本传递给视图,但必须有一种方法可以这样做。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

您不能将@Html.DisplayFor()用作占位符,但可以使用Html.DisplayNameFor()

示例:

@Html.EditorFor(model => model.Test, new { htmlAttributes = new { @class = "form-control", @placeholder = "Your Place Holder" } })

OR

@Html.EditorFor(model => model.Test, new { htmlAttributes = new { @class = "form-control", placeholder = @Html.DisplayNameFor(model => model.Test) } })

答案 1 :(得分:0)

我认为您需要在模型的适当性中添加[Display(name =" Your Text")]属性,如下所示:

[Display (Name="Name Of Client:")]
Public string Name {get; set;}

答案 2 :(得分:0)

在模型中创建一个要传递给视图的属性。

将字符串分配给该属性。

NotImplemented

然后尝试这样: -

__truediv__