Each validation summary linked to it's own partial view

211 Views Asked by At

I have a view that is composed from 2 partial view plus what is already in the page. I want each view to have a validation summary. Everything is working fine except that when there's an error in one of the partials, the message is displayed in every Validation summary so it's there 3 times in the page. I would like to solve that.

I looked online a bit and saw that there is a way to do it like this :

    var SecurityQuestionsErrors = ViewData.ModelState.Where(ms => ms.Key == "SecurityQuestions");
if (SecurityQuestionsErrors.Count()>0)
{
    @Html.ValidationSummary("", new { @class = "" })
}

So I would have this code in every partial view to see if the error is for this one in particular.

When the error comes from the controller ( I can add a key my self, it works fine) :

            catch (FaultException<IncorrectQuestionFault>)
        {
            // question is incorect
            ModelState.AddModelError("SecurityQuestions", Resources.errors.incorrectQuestion);
        }

But when the error comes from the ViewModel it doesnt add the key and im screwed...

        [Required(ErrorMessageResourceName = "IsRequired", ErrorMessageResourceType = typeof(Resources.errors))]
    [StringLength(40, MinimumLength = 7, ErrorMessageResourceName = "NotLongEnough", ErrorMessageResourceType = typeof(Resources.errors))]
    [Display(Order = 0, Name = "question", ResourceType = typeof(Resources.errors))]
    public string question{ get; set; }

So my question is : Am I doing this the good way? Is there a way to add a key to the errors coming from the ViewModel? Should I do this in another way?

All the help is appreciated :D

1

There are 1 best solutions below

2
Robert On

Assuming this is your View model property:

[Required(ErrorMessageResourceName = "IsRequired", ErrorMessageResourceType = typeof(Resources.errors))]
[StringLength(40, MinimumLength = 7, ErrorMessageResourceName = "NotLongEnough", ErrorMessageResourceType = typeof(Resources.errors))]
[Display(Order = 0, Name = "question", ResourceType = typeof(Resources.errors))]
public string question{ get; set; }

@Html.ValidationSummary(false, "", new { @class = "text-danger" })


@Html.LabelFor(x => x.question)
@Html.EditorFor(x => x.question)

This by default would take all validation errors and put them in their own div

If your trying to catch the error on the controller you can:

 if (!ModelState.IsValid)
{
    // the model is invalid

    //if you are trying to catch different errors here
    var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
    //Now you have all the errors and can give specific messages for a given error
    ModelState.AddModelError(string.Empty, "Your error goes here");
}