In ASP.NET MVC, how does response.redirect work?
The conventional mechanism to redirect in ASP.Net MVC is to return an object of type RedirectResult to the client. If this is done before your View method is called, your view methods will never be called.
If you call Response.Redirect yourself, instead of letting Asp.Net MVC's front controller do that for you, your controller method will continue on until it finishes or throws an exception.
The idiomatic solution for your problem is to have your private method return a result that your controller can use.
for example:
public ActionResult Edit(MyEntity entity)
{
if (!IsValid()) return Redirect("/oops/");
...
return View();
}
private bool IsValid()
{
if (nozzle==NozzleState.Closed) return false;
if (!hoseAttached) return false;
return (userRole==Role.Gardener);
}
In ASP.NET MVC, you would normally redirect to another page by returning a RedirectResult
from the controller method.
Example:
public ActionResult Details(int id)
{
// Attempt to get record from database
var details = dataContext.GetDetails(id);
// Does requested record exist?
if (details == null)
{
// Does not exist - display index so user can choose
return RedirectToAction("Index");
}
// Display details as usual
return View(details);
}