jQuery MVC3 在 ajax 调用后重定向到操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10178007/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:54:32  来源:igfitidea点击:

MVC3 redirect to action after ajax call

asp.net-mvc-3jqueryredirect

提问by Youssef

In an ASP.NET MVC3 Application I have a button in the view.

在 ASP.NET MVC3 应用程序中,我在视图中有一个按钮。

When the button is clicked a function is called and it jquery ajax call is made to save items to the database

单击按钮时,将调用一个函数,并调用 jquery ajax 将项目保存到数据库中

    function SaveMenuItems() {
        var encodeditems = $.toJSON(ids);;
        $.ajax({
            type: 'POST',
            url: '@Url.Action("SaveItems", "Store")',
            data: 'items=' + encodeditems + '&[email protected]',
            complete: function () {
                    }
                }
            });
        }

What i want is after the items are saved to the database I want to redirect to another view. (Redirect to action)

我想要的是在项目保存到数据库后我想重定向到另一个视图。(重定向到操作)

How can I do that?

我怎样才能做到这一点?

I tried to use return RedirectToAction("Stores","Store")in the controller at the end of the SaveItemsfunction. But it is not working

我尝试return RedirectToAction("Stores","Store")SaveItems函数结束时在控制器中使用。但它不起作用

I also tried to add window.location.replace("/Store/Stores");in the complete function of the ajax call but didn't work either

我也尝试添加window.location.replace("/Store/Stores");ajax 调用的完整功能,但也没有用

Any help is greatly appreciated

任何帮助是极大的赞赏

Thanks a lot

非常感谢

回答by Shyju

You can use javascript to redirect to the new page. Set the value of window.location.hrefto the new url in your ajax call's success/completeevent.

您可以使用 javascript 重定向到新页面。将 的值设置为window.location.hrefajax 调用的success/complete事件中的新 url 。

var saveUrl = '@Url.Action("SaveItems","Store")';
var newUrl= '@Url.Action("Stores","Store")';

$.ajax({
    type: 'POST',
    url: saveUrl,
    // Some params omitted 
    success: function(res) {
        window.location.href = newUrl;
    },
    error: function() {
        alert('The worst error happened!');
    }
});

Or in the doneevent

或者在done活动中

$.ajax({      
    url: someVariableWhichStoresTheValidUrl
}).done(function (r) {
     window.location.href = '@Url.Action("Stores","Store")';
});

The above code is using the Url.Actionhelper method to build the correct relative url to the action method. If your javascript code is inside an external javascript file, you should build the url to the app root and pass that to your script/code inside external js files and use that to build the url to the action methods as explained in this post.

上面的代码使用Url.Actionhelper 方法构建正确的相对 url 到 action 方法。如果你的JavaScript代码是一个外部JavaScript文件中,你应该建立链接到应用程序根并传递到内外部的js文件,并用它来建立的URL操作方法在解释脚本/代码这个职位

Passing parameters ?

传递参数 ?

If you want to pass some querystring parameters to the new url, you can use this overloadof the Url.Actionmethod which accepts routevalues as well to build the url with the querystring.

如果您想将一些查询字符串参数传递给新的 url,您可以使用Url.Action方法的重载,该方法也接受路由值以及使用查询字符串构建 url。

var newUrl = '@Url.Action("Stores","Store", new { productId=2, categoryId=5 })';

where 2 and 5 can be replaced with some other real values.

其中 2 和 5 可以替换为其他一些实数值。

Since this is an html helper method, It will work in your razor view only,not in external js files. If your code is inside external js file, you need to manually build the url querystring parameters.

由于这是一个 html helper 方法,它仅适用于您的 razor 视图,而不适用于外部 js 文件。如果您的代码在外部 js 文件中,则需要手动构建 url 查询字符串参数。

Generating the new url at server side

在服务器端生成新的 url

It is always a good idea to make use of the mvc helper methods to generate the correct urls to the action method. From your action method, you can return a json strucutre which has a property for the new url to be redirected.

使用 mvc helper 方法生成正确的 action 方法的 url 总是一个好主意。从您的操作方法中,您可以返回一个 json 结构,该结构具有用于重定向新 url 的属性。

You can use the UrlHelperclass inside a controller to do this.

您可以使用UrlHelper控制器内的类来执行此操作。

[HttpPost]
public ActionResult Step8(CreateUser model)
{
  //to do : Save
   var urlBuilder = new UrlHelper(Request.RequestContext);
   var url = urlBuilder.Action("Stores", "Store");
   return Json(new { status = "success", redirectUrl = url });            
}

Now in your ajax call's success/donecallback, simply check the return value and redirect as needed.

现在在您的 ajax 调用的success/done回调中,只需检查返回值并根据需要重定向。

.done(function(result){
   if(result.status==="success")
   {
      window.location.href=result.redirectUrl;
   }
   else
   {
      // show the error message to user
   }
});

回答by faisale

In action you can write this:

在行动中,你可以这样写:

if(Request.IsAjaxRequest()) {
    return JavaScript("document.location.replace('"+Url.Action("Action", new { ... })+"');");  // (url should be encoded...)
} else {
    return RedirectToAction("Action", new { ... });
}

回答by Spencer Ruport

Try

尝试

window.location = "/Store/Stores";

Instead.

反而。