RedirectToAction ignoring Area after routing
I have an Area named 'Subscribers' and a controller in that area named 'SubscriptionsController' with two public action methods: Index() and Unsubscribe() where the Unsubscribe() method is passed a subscriber id i.e. Unsubscribe(int id)
Under certain circumstances (the id is invalid for example), the Unsubscribe() method performs a RedirectToAction("Index") to the other action on the same controller.
public ActionResult Index()
{
return View();
}
if I access the page via '/Subscribers/Subscriptions/Unsubscribe/999' the the RedirectToActionMethod() correctly redirects me to the Index() action.
I wanted to be able to 'shortcut' the formal url ('/Subscribers/Subscriptions/Unsubscribe/999') so I added a route to the Global.ascx file:
routes.MapRoute(
"Unsubscribe",
"Unsubscribe/{id}",
new {area = "Subscribers", controller = "Subscriptions", action = "Unsubscribe"}
);
This route appears to work correctly as it runs the Unsubscribe() method as expected. The problem I have is the calls to RedirectToAction("Index") within Unsubscribe() now fail as they whilst they still invoke the correct action (Index()), the view engine now disregards the Area and tries to load a view relative to the root of the web site '~/Views/Subscriptions/Index.aspx' instead of '~/Areas/Subscribers/Views/Subscriptions/Index.aspx'
I can fix this by modifying the RedirectToAction() method in the Unsubscribe() method thus:
return RedirectToAction("Index", "Subscriptions", new { Area = "Subscribers" });
but this seems like a cumbersome and not v开发者_开发技巧ery flexible solution to the problem.
Any advice or explanation would be much appreciated.
Thanks.
I think I have fixed the problem.
The routing needs to go in the Area's RegisterArea method:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Subscribers_unsubscribe",
"Unsubscribe/{id}",
new { controller = "Subscriptions", action = "Unsubscribe", id = UrlParameter.Optional }
);
context.MapRoute(
"Subscribers_default",
"Subscribers/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
精彩评论