从同一操作返回重定向或 PartialView
我的 Ajax.BeginForm 有问题。我有一个带有提交和更新部分视图的按钮的表单。
我想要实现的是我可以在同一操作中使用以下返回语句。
// button activates this
return PartialView("PartialViewName", data);
现在
// submit activates this
return Redirect(model.Url);
的问题是 Redirect 会导致 Ajax.BeginForm 出现问题
<% using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { OnSuccess = "OnSuccess", UpdateTargetId = "Container", InsertionMode = InsertionMode.Replace }, new { id = "eventAjaxForm" })) { %>
我如何识别结果是 PartialView 还是我们正在重定向用户?
I have a problem with Ajax.BeginForm. I have a form with submit and button that updates partial view.
What I am trying to accomplish is that I could use following return statements in the same Action.
// button activates this
return PartialView("PartialViewName", data);
and
// submit activates this
return Redirect(model.Url);
Now the problem is that Redirect causes problems to the Ajax.BeginForm
<% using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { OnSuccess = "OnSuccess", UpdateTargetId = "Container", InsertionMode = InsertionMode.Replace }, new { id = "eventAjaxForm" })) { %>
How can I identify is the result PartialView or are we redirecting user?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常,当您对控制器操作执行 AJAX 调用时,会遵循任何重定向,直到客户端收到 200 状态代码或错误。因此,您重定向到的 url 的 HTML 将放置在
Container
div 中。另一方面,在控制器操作中,您可以使用 Request.IsAjaxRequest() 测试调用是否异步并返回部分内容。Normally when you perform an AJAX call to a controller action any redirects are followed until the client gets 200 status code or an error. So the HTML of the url you are redirecting to will be placed in the
Container
div. On the other hand in your controller action you could test whether the call was asynchronous usingRequest.IsAjaxRequest()
and return a partial.如果您使用 Post Redirect Get 模式,则需要将 Request.IsAjaxRequest() 与 TempData 结合使用,即将 Request.IsAjaxRequest() 的结果保留在 TempData 中,这样,当您获取重定向请求时,您可以检查 TempData 以查看它是否是原始 Ajax 请求的结果。
Steven Sanderson 的 Pro ASP.NET MVC 2 书中对此进行了很好的解释。
If you are using the Post Redirect Get pattern, you will need to use Request.IsAjaxRequest() in conjunction with TempData, ie, you persist the result of Request.IsAjaxRequest() in TempData, that way, when you get the redirected request, you can check TempData to see if it is the result of an original Ajax request.
This is explained well in Steven Sandersons book on Pro ASP.NET MVC 2.
谢谢你们的回答,但我能够用其他解决方案解决这个问题。
我对提交和部分视图做了单独的操作。部分视图更新是通过以下 jQuery 方法完成的。
并通过“正常”提交按钮完成提交。
Thank you guys for your answers, but I was able to solve the problem with other solution.
I made separate action for the submit and for the partial view. Partial view update is done with following jQuery method.
and submit is done with "normal" submit button.