I have this JavaScript in a page of an ASP.Net MVC project:
function showAllianceMembers_onclick() {
var strName = $("#allianceNameTextBox").val();
$.ajax(
{
type: "POST",
url: "/Alliance/Index",
data: "allianceName=" + strName,
success: function (result) {
if (result.success) {
alert("done!");
}
else {
alert("error!!");
}
},
error: function (req, status, error) {
alert(error);
}
});
}
As you know, this script is calling a MVC Action. here is the MVC Action:
[HttpPost]
public ActionResult Index(string allianceName)
{
//Populating an object containing a list (IList)
return View(res);
}
The problem here is that the JavaScript code just shows the alert with ERROR message…
What’s wrong in my code?
In your controller action you are not sending JSON, but a simple view. So there is no
.successproperty defined on theresultvariable. Here’s how your AJAX request could look like:or if you want to send JSON from your controller action:
and then: