user3131922
user3131922

Reputation: 43

MVC ModelState.IsValid=true with a null required property

I have this Model

public class ModelVM
{
    private string _rD;
    [Required]
    public string RD
    {
        get
        {
            return _rD;
        }
        set
        {
            _rD = RCodes.Contains(value)? value : null;
        }
    }

    private static List<string> RCodes = new List<string>
    {
        "OK",
        "OTHER",
        "ANOTHER"
    };
}

In my MVC Controller

public class MyController : Controller
{
    public ActionResult Index(ModelVM modelVM, FormCollection collection)
    {

        if (!ModelState.IsValid)
            return Json(new
            {
                Result = "ERROR",
                Message = "Missing fields."
            });

        return Json("OK");
    }
}

I send: { RD: "Whatever" }

And in debugging ModelState.IsValid=true. I have a similar code on a WebApi Controller and works as I expect (modelstate.valid=false)

Do you have some ideas why MVC is doing that? or what is wrong with my code?

Upvotes: 2

Views: 2452

Answers (1)

Nkosi
Nkosi

Reputation: 247133

ModelState.IsValid tells you if any model errors have been added to ModelState.

In this case it is valid because there are no client side errors in the provided data that would affect ModelState.

You said...

I sent { RD: "Whatever" }

...which would mean that the model binder will look at the data sent and match the properties with the intended type. From a model binding perspective the [Required] validation was met because when the binder looked at the route value dictionary for the required property RD, it was provided by the client in the incoming data.

If you want to manually invalidate the state you can...

public ActionResult Index(ModelVM modelVM, FormCollection collection)
{
    if(ModelState.IsValid) {
        if(modelVM.RD == null) {
            ModelState.AddModelError("RD", "RD is invalid.");
        }
    }

    if (!ModelState.IsValid)
        return Json(new
        {
            Result = "ERROR",
            Message = "Missing fields."
        });

    return Json("OK");
}

Upvotes: 2

Related Questions