【问题标题】:MVC 4 RedirectToAction Generates Wrong URLMVC 4 RedirectToAction 生成错误的 URL
【发布时间】:2025-12-16 13:05:01
【问题描述】:

我遇到了RedirectToAction 的问题。我有以下简单的控制器类。 Index 方法显示组列表。 Create 创建一个新组并将其添加到数据库中。这工作正常,并在重定向回Index 时显示在列表中。问题是一旦呈现Index 的URL 仍然使用来自Create 的URL:/Group/Create。我认为它实际上正确地重定向到Index,然后立即闪烁到Create 操作,因为它显示了Index 的正确内容。知道什么会导致这种情况吗?我没有定义自定义路由,所以我很确定这不是路由问题。我怀疑这是一个 AJAX 问题。

public class GroupController : Controller
{
    private ModelDb db = new ModelDb();

    [Authorize(Roles = "Administrator")]
    public ActionResult Index()
    {
        return View();
    }

    [Authorize(Roles = "Administrator")]
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "Administrator")]
    public ActionResult Create(Group group)
    {
        if (ModelState.IsValid)
        {
            db.Groups.Add(group);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(group);
    }
}

【问题讨论】:

  • 我怀疑这是 AJAX 问题。?你有什么 ajax 代码?
  • 我正在使用 jQuery Mobile。
  • 你提到了 AJAX。您是否使用 AJAX 发布?

标签: ajax asp.net-mvc-4 iis redirecttoaction


【解决方案1】:

原来这是由 JQuery Mobile 创建的 AJAX 问题。在发布问题之前我应该​​做更多的测试,但也许它会帮助其他人。我禁止使用 AJAX 发布数据,问题就消失了。现在我必须更新一堆表单来禁用它。

所以我现在使用下面的代码来开始一个表单:

@using (Html.BeginForm("Create", "Group", FormMethod.Post, new { data_ajax = "false" }))

【讨论】: