ASP.NET MVC–Display visual hints for the fields in your form


Problem

  • You want to display additional information near a form field in order to help the users complete de form.

  • You want the information to be visible only when the field has focus.

Context

We will use the following model:

public class RegisterModel
{
    [Required( ErrorMessage = "You must specify a username." )]
    [Display(
        Name = "User name" ,
        Description = "Choose something unique so others will know which contributions are yours."
    )]
    public string UserName { get; set; }

    [Required( ErrorMessage = "You must specify an email address." )]
    [DataType( DataType.EmailAddress )]
    [Display(
        Name = "Email address" ,
        Description = "Your email will not be public. It is required to verify your registration and for " +
                        "password retrieval, important notifications, etc."
    )]
    public string Email { get; set; }

    [Required( ErrorMessage = "You must specify a password." )]
    [StringLength( 64 ,
        ErrorMessage = "You must specify a password of {2} or more characters." ,
        MinimumLength = 7 )]
    [DataType( DataType.Password )]
    [Display( Name = "Password" , Description = "Passwords must be at least 7 characters long." )]
    public string Password { get; set; }

    [DataType( DataType.Password )]
    [Display(
        Name = "Confirm password" ,
        Description = "Please reenter your password and ensure that it matches the one above."
    )]
    [Compare( "Password" , ErrorMessage = "The Password and Confirmation Password must match" )]
    public string ConfirmPassword { get; set; }
}

This is a standard RegisterModel that gets created with the MVC3 Internet Application project template. There is a little addition to the model in the form of the DisplayAttribute’s Description property.

In order to show the additional information we will use a jQuery ToolTip plugin from jQuery Tools (see the references section). The plugin requires that each field to have a title attribute so the first task will be to write the value of the Description property into the title attribute.

We will use an Editor Template for the RegisterModel class and we do this by adding a folder called EditorTemplates in the Views\SharedFolder. In order to be picked up automatically by the EditorFor helpers the template needs to have the same name as the class (RegisterModel.cshtml in our case):

RegisterModel.cshtml:

@using Mvc3.Extensions.Demo.Areas.Various.Models
@model RegisterModel
<div class="editor-label">
    @Html.LabelFor( model => model.UserName , null , null , null )
</div>
<div class="editor-field">
    @Html.TextBoxFor( 
        model => model.UserName , 
        new { title = ModelMetadata.FromLambdaExpression<RegisterModel , string>(
            model => model.UserName , ViewData ).Description } )  
    @Html.ValidationMessageFor( model => model.UserName )
</div>
<div class="editor-label">
    @Html.LabelFor( model => model.Email , null , null , null )
</div>
<div class="editor-field">
    @Html.TextBoxFor( 
        model => model.Email , 
        new { title = ModelMetadata.FromLambdaExpression<RegisterModel , string>( 
            model => model.Email , ViewData ).Description } )  
    @Html.ValidationMessageFor( model => model.Email )
</div>
<div class="editor-label">
    @Html.LabelFor( model => model.Password , null , null , null )
</div>
<div class="editor-field">
    @Html.TextBoxFor( 
        model => model.Password , 
        new { title = ModelMetadata.FromLambdaExpression<RegisterModel , string>( 
            model => model.Password , ViewData ).Description } )  
    @Html.ValidationMessageFor( model => model.Password )
</div>
<div class="editor-label">
    @Html.LabelFor( model => model.ConfirmPassword , null , null , null )
</div>
<div class="editor-field">
    @Html.TextBoxFor( 
        model => model.ConfirmPassword , 
        new { title = ModelMetadata.FromLambdaExpression<RegisterModel , string>( 
            model => model.ConfirmPassword , ViewData ).Description } )  
    @Html.ValidationMessageFor( model => model.ConfirmPassword )
</div>

Two things are to be noted here:

  • The value of title attribute is set by calling the static generic method FromLambdaExpression from the ModelMetadata class. The type parameters are the model type from which we want to extract metadata and the type of the property. For parameters we have an expression that identifies the model and the view data dictionary. The function returns a ModelMetadata object and we read the value of the Description property.

We call the template from the Register.cshtml view:

Register.cshtml:

@using ( Html.BeginForm( ) )
{ 
    <fieldset>
        <legend>Register</legend>
        @Html.EditorForModel()
    </fieldset>
    <input type="submit" value="Register" />
}

Everything is set except for the tooltip.

Adding a jQuery Tools Tooltip plugin

We need to add a reference to the jQuery Tools script file and the ToolTip css file (I’ve used the jQuery Tools CDN but the files can be downloaded and added to the project):

<!-- include the Tools -->
<script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/tiny/jquery.tools.min.js"></script>
<!-- tooltip styling -->
<link rel="stylesheet" type="text/css" href="http://static.flowplayer.org/tools/css/tooltip-generic.css"/> 
<!-- javascript coding -->
<script type="text/javascript">
    // execute your scripts when the DOM is ready. this is a good habit
    $(function () {
        // select all desired input fields and attach tooltips to them
        $("form :input").tooltip({
            // place tooltip on the right edge
            position: "center right",

            // a little tweaking of the position
            offset: [-2, 10],

            // use the built-in fadeIn/fadeOut effect
            effect: "fade",

            // custom opacity setting
            opacity: 0.7
        });
    });
</script>

now when the focus enters a field a tool tip will appear on the right with the description set in the Display attribute.

See it in action

ASP.NET MVC 3 - ToolTip

References

jQuery Tools | ModelMetadata class

Download

Download code

 

1 Comment

Comments have been disabled for this content.