asp.net-mvc - ASP.NET MVC 数据注释工具提示

标签 asp.net-mvc asp.net-mvc-3 data-annotations

当表单验证失败时,我被要求显示工具提示而不是纯文本。我们目前正在使用 asp.net MVC 3 数据注释验证器来显示验证错误消息。我对 MVC 还是很陌生,我花了几个小时在线寻找一个干净的解决方案。如果有人能指出我正确的方向,我肯定会很感激。

谢谢

最佳答案

您可以指定要应用于控件的 html 属性。这是使用创建控件的 HtmlHelper 方法的第二个参数完成的。例如,在 MVC 3 中,如果您想要一个带有工具提示的文本框,当您将鼠标悬停在它上面时,请使用这样的 html 标题属性。

@Html.TextBoxFor(model => model.Name, new { @class = "form", @title= "Your name as you would like it to appear in the notification email" })

要在服务器端代码中使用 Controller 中的值,您可以使用 ViewBag(或 MVC2 中的 ViewData)。所以代码看起来像这样:
[HttpPost]
public void Form(Model m)
{
    if(m.Name.Length==0)
        ViewBag.NameError = "Please enter your name";
}

并且 View 代码看起来像这样
@Html.TextBoxFor(model => model.Name, new { @class = "form", @title= (ViewBag.NameError==null?string.empty:(string)ViewBag.NameError)})

关于asp.net-mvc - ASP.NET MVC 数据注释工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4911611/

相关文章:

c# - 显示验证消息,但清除值

ASP.NET MVC - 用于编辑的 ViewModel

javascript - Ajax .BeginForm 在 IE9 中返回空白 View

c# - 在 ValidationMessageFor block 中显示服务器端验证消息

javascript - 如何使用内存流在上传之前预览图像

c# - 建筑问题

asp.net-mvc-3 - 使用掩码验证整数输入 (Asp .NET MVC 3.0)

.net - 如何替换标准 DataAnnotations 错误消息

c# - 索引超出范围。必须是非负误差

c# - 数据注释/验证和动态值