weixin_33749242 2012-03-25 18:45 采纳率: 0%
浏览 31

Ajax提交重定向MVC 3

Although I read dozens of answers I could not find a solution. I'm using MVC 3 with Razor. I have a simple Form with client validation via ajax. This part works fine. My problem is: In the update Action of my Controller I want to redirect to another Action. If the user disables Javacript, this works fine. But with javascript/ajax enabled, the redirectaction doesn't seem to work. Instead it looks like if some kind of partialview or something like that is executed.

My Controller/Action-code:

Function UpdateItem(Item As CItem) As ActionResult

  ' some validation code, save etc.

  if everythingok then
        Return RedirectToAction("Updatesuccess")
  else
        Return RedirectToAction("EditItem")
  endif

End Function

My html page looks like (shortened/pseudo):

Logo image
H1
some text

<form>....</form>

When the form is submitted via ajax the new html code is added beyond "some text", so the form is replaced but everything above the replaced form stays on the page. When ajax/javascript is disabled then after submit a whole new page is loaded. I checked the http headers and noticed, that with ajax there is no redirect (which is logical in some way because it is ajax). What can I do? I want to redirect to a new page.

Is it possible to disable the ajax-submit and only use the "normal" form-submit? I like the client validation via ajax while the user enters data and I want to use this, but for me it would be good enough, if the submit would be a "normal" submit.

I hope someone understands what I want and can help me.

Thanks.

  • 写回答

1条回答 默认 最新

  • from.. 2012-03-25 18:54
    关注

    I'm not a 100% sure I understand your question, but what the heck, don't downvote me :)

    The problem is, redirect works via sending a HttpResponse with the redirect indicated in the headers, which the browser understands. If you submit via AJAX, it's not the browser that handles the request, it's your OWN JS code.

    Here is the trick: instead of returning a redirect, return the Url (preferably as json), and then redirect manually using window.location. I'm not fluent in VB, here is how I'd do it in C#:

    var url = new UrlHelper(this.ControllerContext.RequestContext);
    var link = url.Action("UpdateSuccess");
    return Json(new {link});
    

    and then in jQuery:

        $.ajax({ method: 'POST',
                 url: 'your post url', 
                 success: function(result) {window.location = result.link; },
                 // ... (passing form etc)
         });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题