Reputation: 1819
I have an AJAX call to an MVC ActionResult in a controller, trying to return a bool.
My ajax call:
function CheckForExistingTaxId() {
$.ajax({
url: "/clients/hasDuplicateTaxId",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: JSON.stringify({ taxId: taxId }),
});
}
My method: ("clients" is default route prefix)
[HttpGet, Route("hasDuplicateTaxId")]
public ActionResult hasDuplicateTaxId(string taxId)
{
//if stuff
return Json(true, JsonRequestBehavior.AllowGet);
else
return Json(false, JsonRequestBehavior.AllowGet);
}
I want to open a modal dialog based on the result of the ajax call:
if (CheckForExistingTaxId())
DialogOpen();
First problem is I'm getting a 404 Not Found for clients/hasDuplicateTaxId. Is there a problem with my route or the way I'm calling it? Secondly, am I able to return a boolean value in this way, evaluating the function CheckForExistingTaxId() with the ajax call before opening the dialog?
Upvotes: 2
Views: 3901
Reputation:
Basically if wanting to use Json with HttpGet
:
[HttpGet, Route("hasDuplicateTaxId")]
public ActionResult hasDuplicateTaxId(string taxId)
{
// if 1 < 2
return 1 < 2 ? Json(new { success = true }, JsonRequestBehavior.AllowGet)
: Json(new { success = false, ex = "something was invalid" }, JsonRequestBehavior.AllowGet);
}
ajax:
function CheckForExistingTaxId() {
$.ajax({
url: "/clients/hasDuplicateTaxId",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: JSON.stringify({ taxId: taxId }),
success: function (data) {
if (data.success) {
// server returns true
} else {
// server returns false
alert(data.ex); // alert error message
}
}
});
}
Upvotes: 5