从Ajax调用返回布尔值MVC
问题描述:
我有一个AJAX调用MVC ActionResult在一个控制器,试图返回一个BOOL。从Ajax调用返回布尔值MVC
我的Ajax调用:
function CheckForExistingTaxId() {
$.ajax({
url: "/clients/hasDuplicateTaxId",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: JSON.stringify({ taxId: taxId }),
});
}
我的方法:( “客户” 是默认路由前缀)
[HttpGet, Route("hasDuplicateTaxId")]
public ActionResult hasDuplicateTaxId(string taxId)
{
//if stuff
return Json(true, JsonRequestBehavior.AllowGet);
else
return Json(false, JsonRequestBehavior.AllowGet);
}
我想基于Ajax调用的结果打开一个模态对话框:
if (CheckForExistingTaxId())
DialogOpen();
第一个问题是,我得到一个404没有找到客户/ hasDuplicateTaxId。 我的路线有问题,或者我打电话的方式有问题吗? 其次,我能否以这种方式返回布尔值,在打开对话框之前用ajax调用评估函数CheckForExistingTaxId()?
答
基本上,如果想要使用JSON与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
}
}
});
}
的Ajax考虑的请求成功的,如果它得到的背部 “任何” 数据(因此一个空数组意味着它成功) ,检查你的id是否存在,如果找到了,我会返回id。 然后在你的ajax成功:检查你的数据是否有任何对象。如果这意味着它已经存在。 另一种选择是,如果ID已经存在,并且如果它不返回空的json,则返回一个错误,这样您就可以成功处理“OK”场景:并且错误复制场景: 但是回答你的404问题,这听起来像你没有打你的API,你可以分享你的路线设置? – Puzzle84
所有路线都有“客户”作为前缀,不知道为什么我404'd – noclist