-1

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
Troy Witthoeft
  • 2,498
  • 2
  • 28
  • 37
  • `["id1", boolean status]` is not valid JSON. `["id1", "boolean status"]` would be valid JSON. It's unclear what you want `{"foo":"bar","baz":"Blech"}` to look like. – Pete Feb 19 '13 at 16:39
  • To clarify, what you're showing at the top is a JSON array (an invalid one). What you're showing at the bottom is a JSON object. – Pete Feb 19 '13 at 16:42
  • The invalid JSON format is quoted directly from the article. According to the article, I need the controller to return an array. – Troy Witthoeft Feb 19 '13 at 17:10
  • 1
    You can mix types in a JSON array, but boolean status is two words. Even if one or both were values of some sort, a json array element cannot consist of two things, in this case, boolean and status. if booleanStatus were a variable with a boolean value, for example, that would be a valid JSON array element. So, regardless of whether or not it's quoted from the article, it's invalid JSON. – Pete Feb 19 '13 at 17:24
  • It's clear now that the article author was using invalid syntax. He should have simply replaced "boolean status" with true or false. Rob's answer below created the appropriate response from my controller. – Troy Witthoeft Feb 19 '13 at 17:56

2 Answers2

2

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]
Rob
  • 5,578
  • 3
  • 23
  • 28
0

If you want to return an array within the json, which i think you do. Then you can return a Dictionary. Your not seeing an array in the json output now because of the anonymous type you are passing in is two key values.

public JsonResult MyMethodName(string name)
{
    IDictionary<string, bool> myDict = LoadDictionaryFromSomewhere();
    return Json(myDict, JsonRequestBehaviour.AllowGet);
}
gdp
  • 8,032
  • 10
  • 42
  • 63