Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Data Annotation Tooltip

I have been asked to display tooltips instead of plain text when form validation fails. We are currently using asp.net MVC 3 data annotation validators to display validation error messages. I am still fairly new to MVC and I have spent hours online looking for a clean solution. If someone could point me in the right direction I would surely appreciate it.

Thx

like image 220
user351479 Avatar asked Feb 06 '11 04:02

user351479


1 Answers

You can specify the html attributes that you want to apply to your control. This is done using the second parameter of your HtmlHelper method that creates the control. For example in MVC 3 if you wanted a textbox with a tooltip that appears when you hover over it, use the html title attribute like this.

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

To use a value from your controller in the server side code you can use the ViewBag (or ViewData in MVC2). So the code would look something like this:

[HttpPost]
public void Form(Model m)
{
    if(m.Name.Length==0)
        ViewBag.NameError = "Please enter your name";
}

and the view code would look like this

@Html.TextBoxFor(model => model.Name, new { @class = "form", @title= (ViewBag.NameError==null?string.empty:(string)ViewBag.NameError)})
like image 160
fireydude Avatar answered Sep 17 '22 15:09

fireydude