asp.net-mvc RedirectToAction 不更改 URL 或导航到索引视图

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

RedirectToAction not changing URL or navigating to Index view

asp.net-mvc

提问by kurasa

I tried using a RedirectToActionafter I have done a post to the controller and saved but the URL does not change and the redirect does not seem to work. I need to add that the redirect does enter the controller action method when I debug. It does not change the URL or navigate to the Indexview.

RedirectToAction在向控制器发送帖子并保存后尝试使用 a ,但 URL 没有更改并且重定向似乎不起作用。我需要补充一点,当我调试时,重定向确实进入了控制器操作方法。它不会更改 URL 或导航到Index视图。

public ViewResult Index()
{
    return View("Index", new TrainingViewModel());
}

public ActionResult Edit()
{
    // save the details and return to list
    return RedirectToAction("Index");    
}

What am I doing wrong?

我究竟做错了什么?

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{resource}.js/{*pathInfo}");
    routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = "" } // Parameter defaults
    );
}

jQuery calls:

jQuery 调用:

this.SynchValuesToReadOnly = function() {
    window.location = $('#siteRoot').attr('href') + 'Sites/';           
};

this.OnSiteEdit = function() {
    // post back to the server and update the assessment details    
    var options = {
        target: '',
        type: 'post',
        url: '/Site/Edit',
        beforeSubmit: othis.validate,
        success: othis.SynchValuesToReadOnly
    };

    $('#uxSiteForm').ajaxSubmit(options);
};

回答by Craig Stuntz

The code you show is correct. My wild guess is that you're not doing a standard POST (e.g., redirects don't work with an AJAX post).

您显示的代码是正确的。我的猜测是您没有执行标准的 POST(例如,重定向不适用于 AJAX 帖子)。

The browser will ignore a redirect response to an AJAX POST. It's up to you to redirect in script if you need to redirect when an AJAX call returns a redirect response.

浏览器将忽略对 AJAX POST 的重定向响应。如果您需要在 AJAX 调用返回重定向响应时重定向,则由您在脚本中重定向。

回答by Idris

You need to add "return false;" to end of your onclick javascript event. For example:

您需要添加“返回假;” 结束您的 onclick javascript 事件。例如:

Razor Code

剃刀代码

@using (Html.BeginForm())
{
    @Html.HiddenFor(model => model.ID) 
    @Html.ActionLink("Save", "SaveAction", "MainController", null, new { @class = "saveButton", onclick = "return false;" })
}

JQuery Code

查询代码

$(document).ready(function () {
        $('.saveButton').click(function () {
            $(this).closest('form')[0].submit();
        });
    });

C#

C#

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveAction(SaveViewModel model)
{
    return RedirectToAction("Index");
}

回答by Drew Kennedy

I just came across this issue and nothing was working for me. It turned out the controller I was redirecting to required Authorization - the [Authorize]attribute was preventing any redirection.

我刚刚遇到了这个问题,但没有什么对我有用。结果是我重定向到所需授权的控制器 - 该[Authorize]属性阻止了任何重定向。

[Authorize]//comment this out
public class HomeController : Controller {...}

Down the road or in larger projects this may not be a desired fix, but if you're only looking for a simple redirection or starting out, this may be a solution for you.

在未来或更大的项目中,这可能不是理想的解决方案,但如果您只是在寻找简单的重定向或开始,这可能是您的解决方案。

回答by thiago.adriano26

Try as below:

尝试如下:

return in your action:

在你的行动中返回:

return Json(Url.Action("Index", "Home"));

return Json(Url.Action("Index", "Home"));

and in your ajax:

在你的 ajax 中:

window.location.href

window.location.href

回答by ziya

Check with firebug. Post might be returning a server error.

用萤火虫检查。Post 可能会返回服务器错误。

回答by Kris Kilton

This is a bit late.... but I had the same problem in MVC5. I had 2 actions with the same name, which is common enough. I wasn't getting any errors that I could capture in Application_Error or OnException in the controller. I tried adding in the action, controller, area in the RedirectToAction route variable to no avail. I ended up renaming the POST action to EditPost and everything works now for me. Hope this helps.

这有点晚了......但我在MVC5中遇到了同样的问题。我有两个同名的动作,这很常见。我没有收到任何可以在控制器中的 Application_Error 或 OnException 中捕获的错误。我尝试在 RedirectToAction 路由变量中添加操作、控制器、区域,但无济于事。我最终将 POST 操作重命名为 EditPost,现在一切都对我有用。希望这可以帮助。

public ActionResult Edit(int id)
{
    return View();
}

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Edit(MyInputModel myInputModel)
{
    return View();
}

public ActionResult Create()
{
    return RedirectToAction("Edit", new {id = 1});
}

回答by QMaster

I decided to write this comment as a new answer because I think it needs more description and may someone can't see it in comments if has my problem. So I Apologize if you think this is not an answer and must be written in the comment section.

我决定将此评论写为新答案,因为我认为它需要更多描述,如果有我的问题,可能有人无法在评论中看到它。因此,如果您认为这不是答案并且必须写在评论部分,我深表歉意。

In some cases, I used RedirectToAction to send the user to another action if input values are incorrect or insufficient and avoid continuing the current process as below:

在某些情况下,如果输入值不正确或不足,我使用 RedirectToAction 将用户发送到另一个操作,并避免继续当前过程,如下所示:

if (inputValues == null)
{
  RedirectToAction("index");
}

That keeps not working and continues the current process to take unhandled error. I search and read some articles but I can't find a solution. Calling of RedirectToAction is not from Ajax code and routing is so simple without any parameters even. So why is not working? Finally, I found the simple mistake I did: Forgot to put "return"keyword before RedirectToAction. I changed the code as below:

这一直不起作用并继续当前过程以处理未处理的错误。我搜索并阅读了一些文章,但找不到解决方案。RedirectToAction 的调用不是来自 Ajax 代码,路由也非常简单,甚至不需要任何参数。那么为什么不工作?最后,我发现了我犯的一个简单错误:忘记在 RedirectToAction 之前放置“return”关键字。我将代码更改如下:

if (inputValues == null)
{
  return RedirectToAction("index");
}

And that is worked. Hope this help.

这是有效的。希望这有帮助。

回答by PhiseySt

I just came across this issue and nothing was working for me. It turned out the controller I was redirecting to required Authorization - the [Authorize] attribute was preventing any redirection

我刚刚遇到了这个问题,但没有什么对我有用。结果是我重定向到所需授权的控制器 - [Authorize] 属性阻止了任何重定向

   [Authorize]//comment this out
   public class HomeController : Controller {...}

Because I forgot to add app.UseAuthentication() to the code block in the Startup.cs.

因为我忘记在 Startup.cs 的代码块中添加 app.UseAuthentication()。

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
   ...
   app.UseHttpsRedirection();
   app.UseStaticFiles();
   app.UseAuthentication();
   app.UseMvc(routes =>
   ...

After adding the redirect began to work

添加重定向后开始工作