我已经实现了一个 Controller 来创建新用户。当它成功创建用户时,它会重定向到 Index()
。
我想要的是在一切正常时重定向,但在失败时留在当前页面并查看错误。
我将 jQuery ajax
与 MVC
一起使用。
我的 Controller 如下所示:
[Authorize]
public ActionResult CreateUser(string username)
{
try
{
//here the logic to create the user
}
catch (Exception ex)
{
string error = string.Format("Error creating user: {0}", ex.Message);
Response.StatusCode = 500;
Response.Write(error);
}
return RedirectToAction("Index");
}
用jQuery拦截表单提交,然后用ajax调用:
$("#new-user-form").submit(function() {
var form = $(this);
$.ajax({
type: "GET",
url: form.attr('action'),
data: form.serialize(),
success: function(data, textStatus, xhr) {
//At this point I would like to redirect
},
error: function(xhr, textStatus, errorThrown) {
$(".error-summary").html(xhr.responseText);
}
});
//cancel the event
return false;
});
发生错误时工作正常,但我不知道如何实现成功案例。
我愿意接受其他选择。
最佳答案
如果您要在成功操作中进行重定向,为什么要使用 AJAX? AJAX 的目的是仅刷新站点的部分内容,而不重新加载整个页面。如果在成功的操作中您要进行重定向,则完全违背了您从 AJAX 获得的所有目的和好处。但因为你问了你可以做什么:
[Authorize]
public ActionResult CreateUser(string username)
{
...
if (Request.IsAjaxRequest())
{
return Json(new { redirectToUrl = Url.Action("Index") });
}
return RedirectToAction("Index");
}
然后:
success: function(data, textStatus, xhr) {
window.location.href = data.redirectToUrl;
},
关于jquery - 成功时重定向并失败时显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4493006/