I have a simple MVC 3 application. I want the site to automatically redirect the user somewhere else after they have logged out and been on the logout page for a few seconds. I would like this implemented into the View, but I cannot figure out how to work MVC conventions into something to do this. I know I can use this:
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/Index">
But that means I have to specify a URL, [or if its just /Index it will append it to the current URL, meaning it will call the Action of the Controller (info in brackets is incorrect)]. The only problem is this is my Account controller and I don't want to redirect them (the users) to one of its Actions. I want them redirected to an Action in my Home controller, preferably the Index Action. I imagine this can be done with a new Action in my Account controller, I link there and all that开发者_StackOverflow社区 Action does is redirect to a new View. But that seems like a waste of code. Can I specify directly the controller and action I want in order to do this?
EDIT: Solved it myself. What I said about it appeneding /Index to the current URL was wrong, I can specify the Controller Action there, used:
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/Home/Index">
Worked so far and I didn't have to add the localhost info. This gives me the link localhost:xxxxx/Home/Index
What confused me is if you use this:
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=~/Home/Index">
The link becomes localhost:xxxxx/Account/~/Home/Index
which is really odd since it adds the ~
to the URL link, which normally just means copy the contents beforehand and append to. However it looks like the presence of ~
still means copy the contents beforehand and append everything after, we just also append the ~
this time too.... The Account part of the link is there since the View was called from the Account controller and is in the Account Controller's View folder.
You could use the Url.Action
helper which will take care of generating the proper url based on your routes setup.
Example with Razor:
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=@(Url.Action("Index", "Home"))">
and with WebForms:
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=<%= Url.Action("Index", "Home") %>">
Alternatively you could use javascript to perform the redirect instead of a meta
tag:
<script type="text/javascript">
window.setTimeout(function() {
window.location.href = '@Url.Action("Index", "Home")';
}, 5000);
</script>
You may use like below:
using System.Web.UI;
public ActionResult Index(){
Redirector("Edit", "Home");
return View();
}
private void Redirector(string actionName,string controllerName="") {
string js = "window.setTimeout(function() {$('#preloader').show();window.location.href = '@Url.Action("+actionName+", "+controllerName+")';}, 5000);";
Control ctrl = new Control();
ScriptManager.RegisterClientScriptBlock(ctrl, this.GetType(), "redirect", js, true);
}
精彩评论