Reputation: 21
Am I missing something here? I just want an alert box to give me the string value in my controller action. I keep getting the internal server error message in dev tools
public JsonResult Button_Click()
{
string cam = "Hello";
return Json(cam, JsonRequestBehavior.AllowGet);
}
$("#hello").click(function () {
$.ajax({
url: '/Mycontroller/Button_Click/',
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
failure: function () {
alert("FAIL");
},
error: function () {
alert("ERROR");
}
});
});
});
I should just get an alert box with "Hello" in it.
Upvotes: 2
Views: 243
Reputation: 5069
Instead of writing 'Mycontroller' write only 'My'. 'Controller' suffix is not required.
This should Work
Javascript:
$("#hello").click(function () {
$.ajax({
url: '/My/Button_Click/',
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
failure: function () {
alert("FAIL");
},
error: function () {
alert("ERROR");
}
});
});
Action:
public JsonResult Button_Click()
{
string cam = "Hello";
return Json(cam, JsonRequestBehavior.AllowGet);
}
HTML:
<span id="hello">Click Me</span>
Upvotes: 2
Reputation: 69
public JsonResult Button_Click()
{
string cam = "Hello";
return Json(new { result = true,data=cam }, JsonRequestBehavior.AllowGet);
}
$("#hello").click(function () {
$.ajax({
url: '/Mycontroller/Button_Click/',
type: "GET",
dataType: "json",
contentType:'text/xml; charset=utf-8',
success: function (result) {
if(result.result==true)
{
alert(result.data);
}
},
failure: function () {
alert("FAIL");
},
error: function () {
alert("ERROR");
}
});
});
});
you return direct data so your data not display
my changes help you
Upvotes: 0
Reputation: 1769
your server side code is correct but in javascript you added extra braces,
if i have tried and works fine just remove extra )};
after remove this your script look likes
$("#hello").click(function () {
$.ajax({
url: '/Mycontroller/Button_Click/',
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
failure: function () {
alert("FAIL");
},
error: function () {
alert("ERROR");
}
});
});
i hope it helps you.
Upvotes: 1
Reputation: 905
I was experimenting and it looks like this is working for me:
return new JsonResult(){ Data=cam, JsonRequestBehavior=JsonRequestBehavior.AllowGet };
Instead of:
return Json(cam, JsonRequestBehavior.AllowGet);
As for an explanation, I don't have one [yet]. Strangely, using Post instead of Get in Ajax works fine the old way. I hope it works for you.
Upvotes: 1