ASP.NET MVC How to invoke the other controller's action?
(Solved, look @ the end of this desctiption)
Hi, let's say that I have that URL:
http://mystite.com
then, I use the HomeController
and the Index
action.
but, if the URL looks like
http://mystite.com/itemID
itemID
is a string, it is optional, then I use MyController
and action ViewContent
the Global.asax file:
routes.MapRoute(
"ViewItemContent",
"{itemID}",
new { controller = "My",
action = "ViewContent",
itemID = UrlParameter.Optional
}
);
the problem is, when I user the 1st URL the server treats it as 2nd URL (what's obvious). So, if the itemID
parameter is NULL
how then invoke the HomeController
's Index
action from the MyController
?
I tried
return RedirectToAction("Index", "Home");
but it always redirects me back to the MyController
's ViewContent
action
SOLVED
I solved it by moving the RedirectToAction method from the MyController
's ViewContent
a开发者_开发知识库ction to the HomeController
's Index
action.
I tried to redirect from the MyController
-> Home
and it didn't work.
Now I reversed the redirecting, from Home
-> MyController
by
return RedirectToAction("ViewCategory", "Category", new { itemID = itemID });
and in that case everything works :)
That is because you not configure the route properly. Think and learn how the route works. It can be tricky if your route to the other route quite similar and how it can be fall back to the other route. The sequence is important.
Maybe you just put the "ViewItemContent"
route above the other route. Your solution make another unnecessary round trip to the server because of RedirectToAction
.
Actually you can put another route at the top:
routes.MapRoute(
"Home",
"",
new { controller = "Home",
action = "Index"
}
);
So MVC will look for this first and since http://mystite.com
have nothing at the back, the "Home" route will take precedence and it will use Home
controller with Index
action directly.
精彩评论