簡體   English   中英

返回相同控制器的不同視圖時,URL保持不變

[英]URL stays same when returning different view of same controller

我正在嘗試從控制器返回不同的視圖。 但是,盡管顯示了正確的視圖,但URL保持不變。

這是我在/Company/Create視圖中的表單。

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

因此,基本上,表單和模型將提交給/Company/Create操作。 如果提交的模型有效,那么我將處理數據並使用重定向到/ 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不會立即重定向,而是返回一個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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM