Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC3, returning success JsonResult

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!

like image 384
Expert wanna be Avatar asked May 15 '12 20:05

Expert wanna be


People also ask

What does JsonResult return?

Format-specific Action Results For example, returning JsonResult returns JSON-formatted data. Returning ContentResult or a string returns plain-text-formatted string data. An action isn't required to return any specific type.

What is the difference between ActionResult and JsonResult?

Use JsonResult when you want to return raw JSON data to be consumed by a client (javascript on a web page or a mobile client). Use ActionResult if you want to return a view, redirect etc to be handled by a browser.

How do I return JSON from action method?

The Controller Action method will be called using jQuery POST function and JSON data will be returned back to the View using JsonResult class object. In this article I will explain with an example, how to use the JsonResult class object for returning JSON data from Controller to View in ASP.Net MVC.

Can we directly return JSON?

Then, behind the scenes, it would put that JSON-compatible data (e.g. a dict ) inside of a JSONResponse that would be used to send the response to the client. But you can return a JSONResponse directly from your path operations.


1 Answers

{"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);
   });
});
like image 190
Shyju Avatar answered Oct 13 '22 11:10

Shyju