views:

189

answers:

3

Hi,

We have a model with properties decorated with [Required] which works great for validation. However, what we'd like to do is mark those required fields in the view with an asterisk (or some other style) to denote they are required before the user enters any data for validation.

I don't seem to be able to find anything built into the MVC framework to allow me to do this and therefore wondered if anyone else had already solved this and how?

Ultimately what we're trying to prevent is the need to change code in two places if we subsequently remove a [Required] from a model property.

Many Thanks

+1  A: 

If you are using full form templated helpers EditorFor and DisplayFor you need to customize your own version of Object.ascx.

Brad Wilson has an awesome blog post which outlines this:

http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

What happens it the IsRequired property on ModelMetadata will be true. Inside Object.ascx:

<%=propertu.IsRequired ? "*" : ""%>

If your not using templated helpers you'd have to write your own html helper. What do your views look like?

jfar
+2  A: 

You can build your own HtmlHelper extension for this:

public static string RequiredMarkFor<TModel, TValue>(this HtmlHelper html, Expression<Func<TModel, TValue>> expression)
{
    if(ModelMetadata.FromLambdaExpression(expression, html.ViewData).IsRequired)
         return "*";
    else
         return string.Empty;
}
Gregoire
This was exactly what I was looking for. Many Thanks
Daz Lewis
I cant get this to work. the FromLambdaExpression gives an error about overload method...
Stefanvds
Can you post the errors and your code (perhaps start a new topic)?
Gregoire
+1  A: 

If you are getting an "invalid arguments" error when using "ModelMetadata.FromLambdaExpression", make sure you specify a generic type parameter for HtmlHelper. Here is a revised version of Gregoire's solution:

public static string RequiredMarkFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        if (ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).IsRequired)
            return "*";
        else
            return string.Empty;
    }
Faxanadu