Custom validation using AddModelError for child viewmodel

328 Views Asked by At

I'm having to do some custom validation on a child viewmodel, adding any issues to the ModelState using ModelState.AddModelError(). However I'm presented with an issue trying to get the correct property key.

My parent viewmodel contains N ChildViewModels, where I'm validating a child property:

public class ParentViewModel {
    ...
    public List<ChildViewModel> Children = new List<ChildViewModel>();
}

public class ChildViewModel {
    public int Id { get; set; }
    ...
    public int PropertyToValidate { get; set; }
}

In the view, I iterate over the ChildViewModel collection and display a partial view for each:

@foreach(var child in Model.Children)
    Html.RenderPartial("EditorTemplates/ChildViewModel", child);

This results in the property controls and validation placeholders of each child being rendered as follows, with a unique Name prefix:

<input type="number" name="Children[83d5b826-f8f0-47fe-8985-c45debd1d846].PropertyToValidate">
<span class="field-validation-valid" data-valmsg-for="Children[83d5b826-f8f0-47fe-8985-c45debd1d846].PropertyToValidate" data-valmsg-replace="true"></span>

My question is, how do I get Children[83d5b826-f8f0-47fe-8985-c45debd1d846].PropertyToValidate to use as a key when adding to the ModelStateDictionary?

In my controller I have a collection of invalid ChildViewModel and I've tried adding them to the ModelStateDictionary as follows:

invalidChildViewModels.ForEach(x =>
    ModelState.AddModelError(
        ExpressionHelper.GetExpressionText(x),
        "My custom validation error message"));

But this results in a blank key being added and as such the validation message doesn't get displayed.

0

There are 0 best solutions below