So inside my ASP.NET MVC View I have a conditional statement to redirect users to a different page.
What is the best way to do this?
What is the Controller.RedirectToAction()
equivalent for a View?
So inside my ASP.NET MVC View I have a conditional statement to redirect users to a different page.
What is the best way to do this?
What is the Controller.RedirectToAction()
equivalent for a View?
Your best option would likely be to move the conditional to your Controller and perform the redirection there (this also makes the redirection logic easy to test). Alternatively, you could wrap a JavaScript statement with your View's server-side conditional like so:
<% if (viewShouldRedirect) { %>
<script type="text/javascript">
window.location = "/Your/New/Url";
</script>
<% } %>
This sounds like a perversion of MVC and if you can't do the redirect in the controller, then your logic is not correct.
However, here is what I would use if I didn't have access to the controller for whatever reason:
<meta http-equiv="refresh" content='0;url=<%=Html.Action("MyAction","MyController") %>'>
Update
In your comment, you mentioned it's because you're doing role checking and you don't want to do this in every controller/action. If that's the case, then here is something that you might like to consider:
Create a base controller class and have every controller extend from this class.
In your base controller, have an OnActionExecuting method. In here, you have something like this:
public class MyBaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (/*the user is not in the role desired*/)
{
RedirectToRoute(filterContext, new { controller = "MyController", action = "MyAction"});
}
}
private void RedirectToRoute(ActionExecutingContext context, object routeValues)
{
var rc = new RequestContext(context.HttpContext, context.RouteData);
string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(routeValues)).VirtualPath;
context.HttpContext.Response.Redirect(url, true);
}
}