views:

71

answers:

2

Ok, let's say your view has four partials (each with seperate viewmodels) that are all tied to the main viewmodel. You hit submit and all your data posts up. You run some server side validation and you notice that validation errors occured in fields in 3 of the 4 partials. So, I want to post back the validation errors but above the partial where they belong.

What are your implementation thoughts?

+2  A: 

Interesting scenario. If I understand you correctly: you would like to validate a complex form post and if it's not valid return them to the view and display the error messages above their respective form areas. The reason you can't use <%= Html.ValidationSummary() %> is that you need different summaries for different areas of your form depending on what is valid and what is not?

Take it with a grain of salt but what I would do is write a custom HtmlHelper for each form area or partial. You can base your custom code on the current implementation of Html.ValidationSummary and find the code here. In each custom validation summary you could look for specific errors in ModelState and display those. I don't have much time and haven't tested but this may get you started:

public static class CustomValidationExtensions
{
    public static string CustomValidationSummary(this HtmlHelper htmlHelper)
    {
        if (!htmlHelper.ViewData.ModelState.ContainsKey("YourFormName"))
            return null;

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

        if (modelError == null)
            return null;

        TagBuilder builder = new TagBuilder("span");
        builder.MergeAttribute("class", HtmlHelper.ValidationMessageCssClassName);
        builder.SetInnerText(modelError.ErrorMessage);

        return builder.ToString(TagRenderMode.Normal);
    }
}

This only checks one ModelState element and displays some html. You will want to add all your ModelState elements by hand or loop over the collection and display only the error messages that apply to that partial view. Either way I feel your best bet is adding errors to ModelState the typical way and working directly with ModelState to displaying only the errors that apply to that portion. And of course you can manipulate the html and do whatever you wish with the output.

DM