[英]C# mvc - Controller returns either partial view or json data
I am making an ajax call to the controller. 我正在向控制器进行ajax调用。 The controller will return a string if the execution is successful or it will return a partial view if an error is found.
如果执行成功,控制器将返回一个字符串,如果发现错误,它将返回部分视图。 I am forcing it to fail, but it still goes into the success event in the ajax.
我强迫它失败,但是它仍然会在ajax中进入成功事件。
How do I go about getting it to display the partial view when failed OR just alert the string value when successful? 如何在失败时显示部分视图,或者在成功时仅警告字符串值?
Ajax call: Ajax呼叫:
$.ajax({
url: '@Url.Action("GetItem","Home")',
data: { },
success: function (result) {
alert(result);
},
error: function (result) {
$(".MyDiv").html(result);
}
})
Controller: 控制器:
public ActionResult GetItem([DataSourceRequest]DataSourceRequest request)
{
try
{
throw new Exception("ERROR");
//return Json("Success", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
AlertMessage alertMessage = new AlertMessage();
alertMessage.MessageText = "A critical error has occurred, please contact your administrator.";
alertMessage.ErrorMessageText = ex.ToString();
alertMessage.MessageHeading = "Critical Error";
return PartialView("~/Views/Common/ErrorMessageDisplay.cshtml", alertMessage);
}
}
Function you've provided as error
argument of ajax call will be called if the request fails. 如果请求失败,将调用您作为ajax调用的
error
参数提供的函数。 This means response status code is one of 40* or 50* codes. 这意味着响应状态代码是40 *或50 *代码之一。
But when you're returning PartialView
from your controller, actually response has status code 200 that is "OK" - that's why success function is being called. 但是,当您从控制器返回
PartialView
,实际上响应的状态码为200,即“确定”,这就是调用成功函数的原因。
You can modify your controller code by adding Response.StatusCode = 500;
您可以通过添加
Response.StatusCode = 500;
来修改控制器代码Response.StatusCode = 500;
just before return PartialView(...
, and this should do the trick. 就在
return PartialView(...
之前,这应该可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.