【发布时间】:2020-10-11 22:58:39
【问题描述】:
我知道为什么在 AJAX 完成并期望 JSON 返回时收到此消息。
但是,我对控制器操作方法进行了编码,如果一切正常,则重定向到另一个视图。如果发现错误,则返回 JSON - 错误消息。
从我正在学习的 AJAX 角度来看,无论好(重定向)或错误情况(我返回 JSON),它都会返回 JSON。
那么我如何在 AJAX 中对其进行编码,以识别在我执行重定向并且不以编程方式返回任何内容时没有返回任何 JSON 的情况?
动作方法成功执行,它执行删除,执行重定向但在返回时被捕获,我收到消息:
我的操作方法是:
我有
Task<ActionResult>
如果我尝试
Task<JsonResult>
重定向语句出现错误。
public async Task<ActionResult> DeleteUserProfile()
{
string errorMessage = String.Empty;
try
{
Some code to call the web api...
using (var client = new HttpClient())
{
Some code...
// Call the web api - HTTP POST.
HttpResponseMessage result = await client.PostAsync(restOfUrl, argsData);
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index", "User");
}
else
{
// The web api sent an error response.
errorMessage = "Server error on deleting the user profile. Reason: " + result.ReasonPhrase;
}
}
}
catch (Exception ex1)
{
Some code...
}
// Return a JSON object to show the error message.
return Json(errorMessage, JsonRequestBehavior.AllowGet);
}
我的视图有调用方法的 AJAX:
<input class="btn btn-danger deleteButton" value="Delete Your Profile">
有一个模态窗口,在是,执行 AJAX。而且我认为只有在我推送带有错误消息的 JSON 时它才会回来。
$('.btn-yes11').click(function() {
$('#myModal11').modal('hide');
$.ajax({
type: 'POST',
url: '@Url.Action("DeleteUserProfile", "UserProfile")',
dataType: "json",
success: function(jsondata) {
if (jsondata.length > 0)
{
// Set the error message.
$("#jsonErrorMessage").text(jsondata);
// Show.
$("#jsonErrorMessage").css("display", "block");
}
else
{
// Hide.
$("#jsonErrorMessage").css("display", "none");
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserProfile for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
return true;
});
【问题讨论】:
-
嗨,你有
errorMessage = "Server error on deleting the user profile. Reason:...这不是json。 -
该消息被发回,AJAX 处理它就好了。我在视图中显示它OK。问题是当我有一个好的情况并进行重定向时,它返回时没有 JSON。另外,我如何将其传递回 JSON?
标签: jquery ajax asp.net-mvc