Naigel
Naigel

Reputation: 9644

ASP.NET MVC 5 ModelState.IsValid with json input code

I have an ASP.NET MVC 5 application with a Test class in my model and a ModelTest function in my controller.

I would like to be able to use ModelState.IsValid when I call the action using AJAX, so passing a JSON object. I tried this

public JsonResult Modeltest(Test input) {
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" }, JsonRequestBehavior.AllowGet);
    }

    return Json(new { Response = "Error" }, JsonRequestBehavior.AllowGet);
}

The Test class is pretty straightforward

public class Test {
    public int num { get; set; }
    public string name { get; set; }
}

And the call will be something like this http://myServer/myController/ModelTest?input={"num":5, "name ":"myName"}

Of course it doesn't works and if I put a breakpoint at the first line in the server the input object is NULL. Is no only possible solution pass a JSON string, deserializing it and manually fill a model object? Isn't there a faster (and automated) way to parse the input as the specified class?

Upvotes: 0

Views: 1078

Answers (2)

Luke
Luke

Reputation: 23690

If you POST your values using AJAX or using a form, it will automatically bind your JSON values to your incoming model in your action method.

Here's an example of jQuery code that you could use to post your JSON:

$.post("http://myServer/myController/ModelTest", {"num":5, "name ":"myName"}, function(e) {

    // Success
});

Upvotes: 1

David
David

Reputation: 219027

This:

http://myServer/myController/ModelTest?input={"num":5, "name ":"myName"}

Is a very invalid URL. Query strings are great for simple key/value pairs, for example:

http://myServer/myController/ModelTest?num=5&name=myName

In fact, for a simple object like your Test class, the model binder should be smart enough to interpret these values into an instance of that object. (I'll be very surprised if it doesn't.)

However, if you have a JSON structure (which you may need for more complex objects) then that structure would have to go in the POST body rather than in the query string.

Upvotes: 3

Related Questions