Search code examples
jsonasp.net-mvc-4controllerjquery-validation-engine

How can my MVC controller produce JSON in the following format?


I'm trying to integrate jQuery validation engine with my MVC project to perform inline validation. I have a field inside a jQuery form which is calling to an MVC controller and expects a JSON response. According this article written by the plugin's author...

Now this will send the field in ajax to the defined url, and wait for the response, the response need to be an array encoded in json following this syntax: ["id1", boolean status].

So in php you would do this: echo json_encode($arrayToJs);

How to achieve this in ASP.NET MVC4?

My current controller looks like this.

public JsonResult FunctionName(string fieldValue)
{
        return Json((new { foo = "bar", baz = "Blech" }), JsonRequestBehavior.AllowGet);
}

The response body shows that it returns key value pairs that look like this

{"foo":"bar","baz":"Blech"}

How can I return JSON in the expected format?


Solution

  • The square brackets indicate an array within a JSON object.

    See this article: http://www.w3schools.com/json/json_syntax.asp

    This test code:

    return Json(new object[] { "id1", false }, JsonRequestBehavior.AllowGet);
    

    should return:

    ["id1",false]