10

I need to return JSON data that contain success value (true or false) also, it need to have result message too.

so I using Dictionary to contain data but when it return to Jason data, it contain ""(Quot).

JsonResult = new Dictionary<string, string>();
JsonResult.Add("Success", "False");
JsonResult.Add("Message", "Error Message");
return Json(JsonResult);

it returns,

{"Success":"False","Message":"Error Message"}

but I need,

{Success:False,Message:"Error Message"} //with out "" (Quot)

Anybody know about this?

Thank you!

BZink
  • 7,687
  • 10
  • 37
  • 55
Expert wanna be
  • 10,218
  • 26
  • 105
  • 158

1 Answers1

35
{"Success":"False","Message":"Error Message"}

is valid JSON. You can check it here. in jsonlint.com

You don't even need a Dictionary to return that JSON. You can simply use an anonymous variable like this:

public ActionResult YourActionMethodName()
{
   var result=new { Success="False", Message="Error Message"};
   return Json(result, JsonRequestBehavior.AllowGet);
}

to Access this data from your client, you can do this.

$(function(){
   $.getJSON('YourController/YourActionMethodName', function(data) {
      alert(data.Success);
      alert(data.Message);
   });
});
cda01
  • 1,278
  • 3
  • 14
  • 25
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • +1 I came to write this, although I wouldn't have used a variable, but that's just my preference :) – Mathew Thompson May 15 '12 at 20:21
  • @mattytommo: I love anonymous types in C# in scenarios like this – Shyju May 15 '12 at 20:22
  • The Success key still has to be in quotes, and your code does that. Unless the OP has a typo...he's asking for invalid JSON. Your code returns {"Success":"False","Message":"Error Message"} – BZink May 15 '12 at 20:23
  • @BZink: You are correct. That OP's JSON is valid. should be a problem in his client script. I updated my answer to mention that. – Shyju May 15 '12 at 20:28
  • contentType: 'application/json'; also woriking fine – mzonerz Nov 01 '16 at 06:53