user351479
user351479

Reputation: 253

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

Upvotes: 6

Views: 10870

Answers (2)

Brian Herbert
Brian Herbert

Reputation: 1191

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)})

Upvotes: 7

Matt Tester
Matt Tester

Reputation: 4814

You are most of the way there as you already have the validation errors shown on the page. What you need to be looking at is how to use some client-side scripts (javascript) to be able to render these as a tooltip in the browser.

Take a look at the following JQuery plugins which may be what you are after: http://jquery.bassistance.de/tooltip/demo/

Upvotes: 0

Related Questions