MVC: Can I use ModelState inside class out of controller?

Works well in ASP.NET Core 2 :

//Controller
if (MyValidator.SaveValidation(model, ModelState))
        {
            myManager.Update(model);

            return Json(new
            {
                responseText = "Saved"
            });
        }

//Validator
public static class SaveDossierValidator
{
    public static bool SaveValidation(MyModel model, ModelStateDictionary modelState)
    {
        if (model.property == null) {
            modelState.AddModelError("property", "Error message");
        }

        return modelState.IsValid;
    }
}

You can pass your model state around like this:

public static void test(ModelStateDictionary ModelState)
{
    if (something) ModelState.AddModelError("", "test");
}

And call from inside your controller:

aaa.test(ModelState);

No, you can't. What you're referencing inside Controller is its property, not a class. You can still pass it to the method being called as an argument.

Tags:

C#

Asp.Net Mvc