jQuery 成功时重定向,失败时显示错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4493006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect on success and show error on failure
提问by Daniel Pe?alba
I have implemented a controller to create new users. When it creates the user successfully it redirects to Index()
.
我已经实现了一个控制器来创建新用户。当它成功创建用户时,它会重定向到Index()
.
What I want is to get redirectedwhen all is OK, but stay in the current pageand see the error when something failed.
我想要的是在一切正常时重定向,但留在当前页面并在出现故障时查看错误。
I'm using jQuery ajax
with MVC
.
我正在jQuery ajax
与MVC
.
My controller looks like this:
我的控制器看起来像这样:
[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");
}
The form submit is intercepted with jQuery, and then the call is made with ajax:
表单提交用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;
});
It works fine when an error occurs, but I don't know how to implement the success case.
发生错误时它工作正常,但我不知道如何实现成功案例。
I'm opened to other alternatives.
我对其他选择持开放态度。
回答by Darin Dimitrov
If you are going to redirect in the success action why are you using AJAX? The purpose of AJAX is to refresh only parts of a site without reloading the whole page. If in the success action you are going to redirect that totally defeats all the purpose and benefits you get from AJAX. But because you asked here's what you could do:
如果您要在成功操作中重定向,为什么要使用 AJAX?AJAX 的目的是只刷新站点的一部分而不重新加载整个页面。如果在成功操作中您要重定向,这完全违背了您从 AJAX 获得的所有目的和好处。但是因为你在这里问的是你可以做什么:
[Authorize]
public ActionResult CreateUser(string username)
{
...
if (Request.IsAjaxRequest())
{
return Json(new { redirectToUrl = Url.Action("Index") });
}
return RedirectToAction("Index");
}
And then:
进而:
success: function(data, textStatus, xhr) {
window.location.href = data.redirectToUrl;
},
回答by Hiren Patel
If you are going to redirect in the success action why are you using AJAX? The purpose of AJAX is to refresh only parts of a site without reloading the whole page. If in that any error or session expire you are going to redirect default login page.For that you have to override AuthorizeAttribute Filter so make class belew:
如果您要在成功操作中重定向,为什么要使用 AJAX?AJAX 的目的是只刷新站点的一部分而不重新加载整个页面。如果其中任何错误或会话过期,您将重定向默认登录页面。为此,您必须覆盖 AuthorizeAttribute 过滤器,因此请创建类:
public class CheckAuthorization : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (HttpContext.Current.Session["AFSUserId"] == null || !HttpContext.Current.Request.IsAuthenticated)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 302; //Found Redirection to another page. Here- login page. Check Layout ajaxError() script.
filterContext.HttpContext.Response.End();
}
else
{
filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?ReturnUrl=" +
filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
}
}
}
After Making that CheckAuthorization Class you have just put whenever you call ajax Authorization like below:
在创建 CheckAuthorization 类之后,只要您像下面这样调用 ajax Authorization 就可以放置:
[CheckAuthorization]
public class BuyerController : Controller
{
[HttpGet()]
public ActionResult GetOrderlist()
{
return View();
}
}
now you have to handle ajax status 302 in view side on each Ajax call so put line of code in your layout page order by leadid desc any particular page so like below:
现在,您必须在每个 Ajax 调用的视图侧处理 ajax 状态 302,因此将代码行按 Leadid desc 放在您的布局页面顺序中的任何特定页面,如下所示:
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.status == 302) {
window.location.href = '@Url.Action("Login", "Home")';
}
});
Here you are redirect to login page if current session expire or Timeout.
如果当前会话过期或超时,您将在此处重定向到登录页面。
回答by Tony Wall
Here is an alternative answer which uses pure MVC classes and you don't have to hardcode any script or use jQuery. First, I found the validators of MVC 2 work fine in success, failure and confirm cases as long as you remember:
这是一个使用纯 MVC 类的替代答案,您不必硬编码任何脚本或使用 jQuery。首先,我发现 MVC 2 的验证器在成功、失败和确认案例中都可以正常工作,只要你还记得:
1) Include necessary MVC scripts (three in total plus EnableClientSideValidation call - see MSDN).
1) 包括必要的 MVC 脚本(总共三个加上 EnableClientSideValidation 调用 - 请参阅 MSDN)。
2) Put MetadataClassAttribute and RequiredAttribtues on your model/data entities. You don't have to create separate metadata classes and make your model partial (I find that pants) just reference the same model class in the attribute.
2) 将 MetadataClassAttribute 和 RequiredAttributes 放在您的模型/数据实体上。您不必创建单独的元数据类并使您的模型部分(我发现那条裤子)只需在属性中引用相同的模型类。
3) Solve the AJAX redirect issue by returning JavaScript as already suggested (but in a jQuery orientated way)...
3) 通过按照已经建议的方式返回 JavaScript 来解决 AJAX 重定向问题(但以 jQuery 为导向的方式)...
I only suffered strange behaviour during validation when it already failed to redirect from the list page to a details/edit page. The error messages would appear for a few seconds then disappear! Of course it was confused because the shell of the page was the first list page and the inner contents from the edit page. So the root cause of the problem was the out-the-box MVC 2 toolkit failing to redirect properly from the first page, not that the validators were not working properly on the second page.
当它已经无法从列表页面重定向到详细信息/编辑页面时,我只在验证期间遇到了奇怪的行为。错误信息会出现几秒钟然后消失!当然它很困惑,因为页面的外壳是第一个列表页面和编辑页面的内部内容。因此,问题的根本原因是开箱即用的 MVC 2 工具包无法从第一页正确重定向,而不是验证器在第二页上无法正常工作。
I found the same solution here:
我在这里找到了相同的解决方案:
http://craftycodeblog.com/2010/05/15/asp-net-mvc-ajax-redirect/...which I expanded into an extension method and class in VB.NET:
http://craftycodeblog.com/2010/05/15/asp-net-mvc-ajax-redirect/...我在VB.NET中扩展为一个扩展方法和类:
''' <summary>
''' MVC extension methods.
''' </summary>
Public Module MvcExtensions
''' <summary>
''' Returns an <see cref="AjaxAwareRedirectResult"/> for the specified action
''' and optional controller name.
''' </summary>
<Extension()> _
Public Function AjaxAwareRedirectToAction(controller As Controller, _
actionName As String, _
Optional controllerName As String = Nothing) _
As RedirectResult
' Get target URL
Dim url = controller.Url.Action(actionName, controllerName)
' Return AJAX aware redirect result
Return New AjaxAwareRedirectResult(url)
End Function
End Module
''' <summary>
''' <see cref="RedirectResult"/> which works with MVC 2 AJAX.
''' </summary>
''' <remarks>
''' Normal redirects do not work with AJAX partial updates in MVC (HTTP 302 status).
''' With MVC 2 AJAX it is necessary to return JavaScript to change the browser location.
''' </remarks>
Public Class AjaxAwareRedirectResult
Inherits RedirectResult
''' <summary>
''' Creates an instance which redirects to the specified URL using
''' a response containing either AJAX JavaScript or classic HTTPS 302 status.
''' </summary>
''' <param name="url">Target URL.</param>
Sub New(url As String)
MyBase.New(url)
End Sub
''' <summary>
''' Generates the response.
''' </summary>
Public Overrides Sub ExecuteResult(ByVal context As ControllerContext)
' Check if AJAX was used for request
If context.RequestContext.HttpContext.Request.IsAjaxRequest Then
' Perform JavaScript redirect when AJAX is used
Dim destinationUrl As String = UrlHelper.GenerateContentUrl(Url, context.HttpContext)
Dim result As JavaScriptResult = New JavaScriptResult With {
.Script = ("window.location='" + destinationUrl + "';")}
result.ExecuteResult(context)
Else
' Perform classic HTTP 302 status redirect
MyBase.ExecuteResult(context)
End If
End Sub
End Class
So then you have two options. You can follow the typical MVC pattern of calling AjaxAwareRedirectToAction(aciton, [controller]) for MVC targets, or return a new instance of an AjaxAwareRedirectResult(url) when you have a specific URL target in mind (i.e. external site).
那么你有两个选择。您可以遵循为 MVC 目标调用 AjaxAwareRedirectToAction(aciton, [controller]) 的典型 MVC 模式,或者当您有特定的 URL 目标(即外部站点)时返回 AjaxAwareRedirectResult(url) 的新实例。
I was really surprised that Microsoft didn't get AJAX redirects sorted in the first MVC 2 RTM. I have to use MVC 2 on my current project which is why I have to suffer this limitation, but also have some newer MVC solutions which I see are leaning more towards jQuery for validation. I will find out soon if they fixed it.
我真的很惊讶 Microsoft 没有在第一个 MVC 2 RTM 中对 AJAX 重定向进行排序。我必须在我当前的项目中使用 MVC 2,这就是为什么我必须遭受这个限制,但也有一些更新的 MVC 解决方案,我认为这些解决方案更倾向于使用 jQuery 进行验证。我很快就会知道他们是否修复了它。