【问题标题】:URL stays same when returning different view of same controller返回同一控制器的不同视图时,URL 保持不变
【发布时间】:2012-06-30 17:41:06
【问题描述】:

我正在尝试从我的控制器返回不同的视图。但是,尽管显示了正确的视图,但 URL 保持不变。

这是我在/Company/Create 视图中的表单。

@using (Html.BeginForm("Create", "Company", FormMethod.Post)) 
{ 
 // Form here
}

所以基本上,表单和模型都提交给/Company/Create action。如果提交的模型是有效的,那么我处理数据并重定向到 /Company/Index 视图与

return View("Index");

正如我所说,显示了正确的视图,但是 URL(地址栏)仍然是 http://.../Company/Create

我试过RedirectToAction("Index"); 它也不起作用。而且我认为它不是一个好的 MVC 实践。我有一个单一的布局和公司视图呈现RenderBody()

有什么想法吗?

谢谢。

编辑:

这是我的操作方法,

[HttpPost]
public ActionResult Create(CompanyCreate model)
{
    /* Fill model with countries again */
    model.FillCountries();

    if (ModelState.IsValid)
    {
        /* Save it to database */
        unitOfWork.CompanyRepository.InsertCompany(model.Company);
        unitOfWork.Save();
        RedirectToAction("Index");
        return View();
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

【问题讨论】:

  • 您可以发布该操作的完整代码吗?返回视图不会更改它不应该更改的 url,但是我很惊讶 redirecttoaction 没有按照您的预期进行。我也不会称之为不好的做法,因为它有助于双张贴。
  • 感谢评论。添加了操作代码。

标签: c# asp.net-mvc model-view-controller controller


【解决方案1】:

如果您想更改 url,您需要重定向到另一个操作。

但是RedirectToAction 不会立即重定向,而是返回一个RedirectToRouteResult 对象,它是一个ActionResult 对象。

所以您只需从您的操作中返回RedirectToAction 的结果:

[HttpPost]
public ActionResult Create(CompanyCreate model)
{
    /* Fill model with countries again */
    model.FillCountries();

    if (ModelState.IsValid)
    {
        /* Save it to database */
        unitOfWork.CompanyRepository.InsertCompany(model.Company);
        unitOfWork.Save();
        return RedirectToAction("Index");
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

【讨论】:

  • 谢谢。我来自经典的网络表单。我认为它类似于 Response.Redirect("url")。我的错 :) 再次感谢。
猜你喜欢
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多