views:

129

answers:

1

OK - at the moment, to validate my pages I am using [Required] in my model in an MVC2 C# project.

For eg in my model I have:

[DisplayName("Username")]
[Required(ErrorMessage = "Please enter a Username")]
public string UserName { get; set; }

... and in my view I have

<%=Html.ValidationMessageFor(x => x.UserName, "*")%>

But then this isn't consistent with the rest of the styling and error trapping of the rest of our site which was written in Classic ASP.

I want to be able to recreate if possible the validation styles in the images below.

So on loading the page (not on submitting) we might see a display similar to this, with alt and title of the M icon displaying "Please enter a Username":

Mandatory Fields

And then if we try and submit with missing values - we see

Error Messages

Again hovering over the red x will display the error message.

Is there a straightforward way of achieving this styling of validation and if so what is the best way to go about it...

Thank you for any helpful hints, tips, suggestions:

+1  A: 

You should beable to achieve this by creating your own HtmlHelper extension method.

E.g.

public static string ValidationImage(this HtmlHelper htmlHelper, string modelName)
{
    if (modelName == null)
    {
        throw new ArgumentNullException("modelName");
    }

    if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName))
    {
        return null;
    }

    ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
    ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
    ModelError modelError = ((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors[0];

    if (modelError == null)
    {
        return null;
    }

    string messageText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState);

    TagBuilder builder = new TagBuilder("img");
    builder.MergeAttribute("src", "urlToYourCrossImage");
    builder.MergeAttribute("class", HtmlHelper.ValidationMessageCssClassName); //Or your own custom class for the img tag here
    builder.MergeAttribute("alt", messageText);
    builder.MergeAttribute("title", messageText);

    return builder.ToString(TagRenderMode.SelfClosing);
}

Have a look at the ASP.NET MVC ValidationExtensions source code to get some ideas about how to write some overloads for it.

HTHs,
Charles

Charlino
Hi Charlino, this is a good answer which should solve part of the problem - but what the part that mentions I want to show Mandatory fields before form submission with the blue M... Is there a way to take that info from the [required] fields in the model... just want to know the best approach to this. Many thanks for your answer.
beebul
Thanks Charlino - I have managed to get this working on your advice...
beebul