Question

I have a viewModel that contains an object. I've defined a custom editor template for that object, which allows me to edit each of the children of that object. The children values aren't required serverside (so I don't have any Required annotations), however if the user reaches this particular input, it should be required.

Is there any way I can inspect the values of these children objects (within the viewModel) in the POST method, and return some errors to the view if they are null?

I'm using Razor.

Was it helpful?

Solution 2

What you can do is to write a function that will be check user input (on change in that field)

if the user reaches this particular input

and if user reaches that particular input you use jQuery to add @class = "required" HTML attribute to your object. From that moment on it will become required

Take a look here: this is jQuery validator for required field based on some condition. I think this is exactly what you're after

Edit

Your other option is to use AJAX to go back to server to verify what you're looking for. Example is here

Hope this makes sense and is of help to you.

OTHER TIPS

On the server-side, you could check the child objects of the class in your action,

[HttpPost]
public ActionResult Edit(MyClass myClass)
{
    if (myClass.Children.Any(child => child == null))
    {
        foreach(var child in myClass.Children
            .Where(child => child == null)
            .Select((item, index) => new { Item = item, Index = index))
        {

             ModelState.AddModelError(
                 string.Format("Children[{0}]", child.Index), 
                 "Must be required");
        }

        return this.View("...");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top