Reputation: 8678
I'm passing some string messages as Json object in view.
public ActionResult SomeAction(someObject object)
{
.....
.....
if (check1)
{
return Json(new { error = Resource.someMessage1},JsonRequestBehavior.AllowGet);
}
if(check2)
{
return Json(new { error = Resource.someMessage2}, JsonRequestBehavior.AllowGet);
}
//some stuffs
return Json(new {success = "success"}, JsonRequestBehavior.AllowGet);
}
I want to retrieve the messages passed from controller and alert from My view
in view I have some javascript
function done(data) {
alert("hello");
var message = JSON.parse(data);
alert(message);
if (message["error"] != undefined) {
alert(message["error"]);
} else {
//do some stuff
}
};
what I was expecting is if passed message from controller is type error then I would get alert with the message.
The line alert("hello");
but there is no alert after that.
I get error in console
Am I doing something wrong?
Upvotes: 1
Views: 525
Reputation: 3596
the variable type is detected as json object.
var x = {"error":"somemessage"};
alert(x.error)
The variable is detected as String here.
var x = JSON.parse('{"error":"somemessage"}');
alert(x.error)
If you notice, the difference is #1 starts with {(curly braces) whereas #2 starts with '(apostrophe)
Upvotes: 1
Reputation: 4753
You have to use data.sucess
to get your result . There is no need to parse again.
Upvotes: 0
Reputation: 1120
Try not parsing the answer (so remove "JSON.parse(data)" line) and read everything directly from "data" variable.
Upvotes: 0
Reputation: 47774
If you execute the following line of code
var a = { success : "success" };
var b = JSON.parse(a);
you will get the error you have mentioned about "SyntaxError: Unexpected token o..."
Don't know why are you trying to convert your already JSON object using JSON.parse(), instead you could use this
a.success
to read the "success" value .
Upvotes: 2