I am trying to return a different view from my controller. However, although the correct view is displayed the URL stays same.
This is my form in /Company/Create
view.
@using (Html.BeginForm("Create", "Company", FormMethod.Post))
{
// Form here
}
So basically, the form and model is submitted to /Company/Create
action. If the submitted model is valid, then I process the data and redirect to /Company/Index view with
return View("Index");
As I said, correct view is displayed however, URL (address bar) is still http://.../Company/Create
I tried RedirectToAction("Index");
It does not work also. And I do not think its a good MVC practice. I have a single layout and Company views are rendered with RenderBody()
Any ideas ?
Thanks.
Edit :
This is my action method,
[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);
}
You need to redirect to another action if you want the url changed.
However RedirectToAction doesn't redirect instantly but returns a RedirectToRouteResult
object which is an ActionResult
object.
So you just need to return the result of RedirectToAction
from your action:
[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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.