RedirectToAction不起作用

kur*_*asa 31 asp.net-mvc

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");    
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?

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
    );
}
Run Code Online (Sandbox Code Playgroud)

// JQUERY CALLS

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);
};
Run Code Online (Sandbox Code Playgroud)

Cra*_*ntz 75

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

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

  • 当您执行异步`POST`时,如果获得重定向响应,则必须手动重定向(在JS中).浏览器不会自动执行此操作.这就是关于这一点的所有内容.浏览器假设脚本在这种情况下负责. (2认同)
  • 就像我这样的n00bs补充和提供一些指导.在ajax.beginform指令中,包含类似这样的新AjaxOptions {OnSuccess ="window.location.href ='ControllerName/Action'"}和voilá (2认同)

小智 7

你需要添加"return false;" 结束你的onclick javascript事件.例如:

剃刀代码

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

JQuery代码

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

C#

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

  • 出于某种原因,我总是忘记了"返回"是必需的.猜猜我已经习惯了从不需要"返回"的旧Response.Redirect. (5认同)

thi*_*o26 5

尝试如下:

在你的行动中返回:

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

在你的 ajax 中:

window.location.href


Dre*_*edy 5

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

[Authorize]//comment this out
public class HomeController : Controller {...}
Run Code Online (Sandbox Code Playgroud)

在路上或在较大的项目中,这可能不是一个理想的修复,但如果您只是寻找一个简单的重定向或开始,这可能是一个解决方案.