如何在C# / MVC 4中使用Html.TextBoxFor输入占位符文本

30

通常在HTML/CSS中,如果您想要向文本框添加占位符文本,只需执行以下操作:

<input type="text" class="input-class" placeholder="请输入您的电子邮件"/>

但是,由于我正在使用Visual Studio MVC 4中提供的现有登录面板代码:

/Views/Account/Login.cshtml

这是当前呈现输入字段的C#代码:

@Html.TextBoxFor(m => m.Email, new { @class = "form-input" })
@Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })

@Html.PasswordFor(m => m.Password, new { @class = "form-input" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

输入图片描述

如何在C#代码中添加占位文本?我尝试了以下代码:

@Html.TextBoxFor(m => m.Email, placeholder ="Email" new { @class = "form-input" })

它用红色下划线标出了“placeholder”,并显示“当前上下文中不存在名称为'placeholder'的内容”。

6个回答

70

使用带有 htmlAttributes 参数的 TextBoxFor() 方法重载。该参数应为一个匿名对象,包含您要分配给输入的 所有 属性。

例如,如果您想设置 placeholderclass 属性:

@Html.TextBoxFor( m => m.Email, new { placeholder = "Email", @class = "form-input" } )

11

请尝试以下操作

这段代码已经经过测试,确保可用

@Html.TextBox("CustomarName" ,null, new { @class = "form-control" , @placeholder = "Search With Customar Name" })

希望对您有所帮助


2
OP正在询问如何在TextBoxFor中使用占位符,而不是在TextBox中使用。 - Dush
那是我真正寻找的答案 :-) - Mariusz

6

这对我来说很有效...

@Html.TextBoxFor(m => m.Username, new { @placeholder = "Username", @class = "input100" })

4

关于输入字段

@Html.TextBoxFor( m => m.Email, new { placeholder = "Your email id" })

对于文本域

@Html.TextAreaFor(m => m.Description, new { placeholder = "Please add description here" })

4

试试这个:

@Html.TextBoxFor(m => m.Email, new { placeholder = "Email" })

如果我这样做:@Html.TextBoxFor(m => m.Email, new { placeholder = "Email" }, new { @class = "text-danger" }) 它会用红色下划线标出 new { placeholder = "Email" } 并显示“Argument 3: cannot convert from '<anonymous type: string placeholder>' to 'string'” - 我认为它仍然需要 text-danger 类,但我可以尝试将其删除。编辑 删除类起作用了 - text-danger 是一个引导类,用于定义占位符文本颜色。实际上,我仍然想定义占位符文本颜色。 - HappyHands31
你实际上是用 new {placeholder = "Email"} 创建了一个新对象。因此,您可以包含任何其他HTML属性;它们都不是必需的。您甚至可以将其保留为空白。 - Yatin

2

有一个参数叫做ObjectHtmlAttributes,您可以在那里设置每个html输入属性
例如:

 @Html.TextBox("Model binding here" , new { @class="form-controll" , @placeholder="Enter email"})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接