【问题标题】:How to Enter Placeholder Text Within Html.TextBoxFor in C# / MVC 4如何在 C#/MVC 4 中的 Html.TextBoxFor 中输入占位符文本
【发布时间】:2017-10-16 06:08:09
【问题描述】:

通常在 HTML / CSS 中,如果您想将占位符文本添加到文本框,您只需这样做:

<input type="text" class="input-class" placeholder="Please enter your email"/>

但由于我使用的是为 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" })

它用红色下划线“占位符”表示“当前上下文中不存在名称'占位符'”。

【问题讨论】:

    标签: c# html css asp.net asp.net-mvc-4


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 如果我这样做:@Html.TextBoxFor(m => m.Email, new { placeholder = "Email" }, new { @class = "text-danger" }) 它会在红色下划线 new { placeholder = "Email" } 并说“参数 3:无法从 '' 转换为 'string'” - 我认为仍然需要 text-danger 类,但我可以尝试删除它。 编辑 删除类有效 - text-danger 是一个引导类,用于定义占位符文本颜色。但实际上,我仍然想定义占位符文本颜色。
    • 您实际上是在使用new {placeholder = "Email"} 创建一个新对象。因此,您可以包含任何其他您想要的 html 属性;它们都不是强制性的。您甚至可以将其留空。
    【解决方案2】:

    使用TextBoxFor() 的重载和htmlAttributes 参数。该参数应该是一个匿名对象,具有您希望分配给输入的 all 属性。

    例如,如果要设置placeholderclass 属性:

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

    【讨论】:

      【解决方案3】:

      有一个参数是 objecthtmlattributes ,你可以在那里设置每个 html 输入属性
      示例:

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

      【讨论】:

        【解决方案4】:

        尝试以下方法

        此代码已经过测试并且可以正常工作

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

        希望对你有帮助

        【讨论】:

        • OP 询问如何在TextBoxFor 中而不是在TextBox 中使用占位符
        • 这正是我一直在寻找的答案 :-)
        【解决方案5】:

        对于输入字段

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

        对于文本区域

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

        【讨论】:

          【解决方案6】:

          这对我有用...

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

          【讨论】:

            猜你喜欢
            • 2022-07-02
            • 2015-12-17
            • 1970-01-01
            • 2014-10-29
            • 1970-01-01
            • 1970-01-01
            • 2020-10-12
            • 1970-01-01
            • 2011-11-16
            相关资源
            最近更新 更多