【问题标题】:RedirectToAction not changing URL or navigating to Index viewRedirectToAction 不更改 URL 或导航到索引视图
【发布时间】:2010-02-08 21:35:43
【问题描述】:

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

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

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

我做错了什么?

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 调用:

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);
};

【问题讨论】:

  • 您显示的代码是正确的。我的疯狂猜测是您没有执行标准 POST(例如,重定向不适用于 AJAX 帖子)。你能显示更多代码吗?
  • aaaaahhh....不知道。是的你是对的。它确实来自 jquery 中的 ajax 帖子,这意味着如果成功,我应该从那里重定向。没问题。将您的评论作为“答案”提出,如果您愿意,我会在证明它有效时标记谢谢

标签: asp.net-mvc


【解决方案1】:

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

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

【讨论】:

  • 好答案。你能为我们解释一下为什么吗?
  • 当您执行异步 POST 时,如果您收到重定向响应,则必须手动重定向(在 JS 中)。浏览器不会自动执行此操作。这就是所有要说的。在这种情况下,浏览器假定脚本负责。
  • 只是对像我这样的 n00bs 进行补充和指导。在 ajax.beginform 指令中,包含类似这样的内容 new AjaxOptions{ OnSuccess="window.location.href = 'ControllerName/Action'" } 和瞧
  • @Craig Stuntz 实际上 Chrome 和 FF 的自动重定向非常好。 IE(在我的例子中是 11 版)没有……但我认为在发帖时没有。
【解决方案2】:

你需要加上“return false;”结束您的 onclick javascript 事件。例如:

剃刀密码

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

JQuery 代码

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

C#

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

【讨论】:

  • 出于某种原因,我总是忘记“return”是必需的。猜猜我已经习惯了从不需要“返回”的旧 Response.Redirect。
【解决方案3】:

尝试如下:

回报你的行动:

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

在你的 ajax 中:

window.location.href

【讨论】:

    【解决方案4】:

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

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

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

    【讨论】:

    • 现在我明白了为什么我在尝试重定向时总是被定向到登录,呵呵。谢谢!!
    【解决方案5】:

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

    【讨论】:

      【解决方案6】:

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

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

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

      这仍然无法正常工作并继续当前进程以处理未处理的错误。我搜索并阅读了一些文章,但找不到解决方案。 RedirectToAction 的调用不是来自 Ajax 代码,而且路由非常简单,甚至没有任何参数。那么为什么不工作呢?最后,我发现了我犯的一个简单错误:忘记在 RedirectToAction 之前放 "return" 关键字。我将代码更改如下:

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

      这是有效的。希望对您有所帮助。

      【讨论】:

        【解决方案7】:

        这有点晚了......但我在 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});
        }
        

        【讨论】:

          【解决方案8】:

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

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

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

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

          添加重定向后开始起作用

          【讨论】:

            猜你喜欢
            • 2012-02-11
            • 1970-01-01
            • 2013-12-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多