我在部分 Razor View 上使用 $ajax jquery 函数来获取另一个部分 View 以及从 Controller 到页面的强类型模型数据--> 显示在特定的 div 中。现在,如果数据模型数据存在,它就可以工作,但如果没有模型数据,我将传递 json 响应,以便我可以检查 razor View 以避免空异常。我的问题是 $ajax 中的 done 方法没有调用 plus json 响应,我不知道我哪里做错了
Ajax函数
$(document).ready(function () {
/*Address*/
$.ajax({
url: '@Url.Action("DisplayStudentAddress")',
type: "GET",
cache: false
}).done(function (data, textStatus, jqXHR) {
alert(data.Response);
$('#studentAddressDisplay').html(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(jqXHR +" "+textStatus+" "+errorThrown);
});
});
ActionResult 方法
[HttpGet]
[Authorize]
public ActionResult DisplayStudentAddress()
{
int _studentEntityID = 0;
_studentEntityID = _studentProfileServices.GetStudentIDByIdentityUserID(User.Identity.GetUserId());
Address _studentAddressModel = new Address();
_studentAddressModel = _studentProfileServices.GetStudentAddressByStudentID(_studentEntityID);
if (_studentAddressModel != null)
{
return PartialView("DisplayStudentAddress_Partial", _studentAddressModel);
}
else
{
return Json(new { Response = "Provide Your Address Detail!" });
}
}
#endregion
我检查了调试,在 Controller 中调用了 json,但它在 ajax 中提示错误
最佳答案
如果您的服务器为 json 响应返回空字符串,jQuery 会将其视为失败。空字符串被认为是无效的 json。
根据官方文档here .
As of 1.9, an empty string returned for JSON data is considered to be malformed JSON (because it is); this will now throw an error.
尝试使用下面的代码代替 .always
:-
$.ajax({
url: '@Url.Action("DisplayStudentAddress")',
type: "GET",
cache: false
}).always(function (data, textStatus, jqXHR) {
alert(data.Response);
$('#studentAddressDisplay').html(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(jqXHR +" "+textStatus+" "+errorThrown);
});
因为 .done
仅在一切正常时执行,所以如果出现问题,.done
将不会被调用。但是无论您的 ajax 请求是否有效,always
方法总是会被触发。
关于c# - $ajax 完成功能在 ASP.NET -MVC5 应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31581677/