In my mvc application I have Admin area and have default controllers outside area. I want to define route in global.asax file so that both default and admin.
like if user type: {http://localhost/} -> open default route
if user type: {http://localhost/Admin/} -> open admin route
If someone has idea to handle this then please suggest.
Create an Admin area registration file. Such as:
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Admin", action = "Index", id = UrlParameter.Optional },
new[] { "Admin.Controllers" }
);
}
}
Then call this from your Global.asax
AreaRegistration.RegisterAllAreas();
Related
Let's say I have an area named Admin in my MVC application. This area has a HomeController with an Index action like so:
using System.Web.Mvc;
namespace AreasPractice.Areas.Admin.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return Content("Admin.HomeController");
}
}
}
The area registration for the Admin area has the following defaults for the area related route:
using System.Web.Mvc;
namespace AreasPractice.Areas.Admin
{
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
//, new[] { "AreasPractice.Areas.Admin.Controllers" }
);
}
}
}
My application's root area also has a HomeController with an Index action and a route config like so:
using System.Web.Mvc;
namespace AreasPractice.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return Content("From home controller of the root");
}
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
, namespaces: new[] { "AreasPractice.Controllers" }
);
}
}
Now, I add an AdminController with an Index action in the root area of my application like so:
using System.Web.Mvc;
namespace AreasPractice.Controllers
{
public class AdminController : Controller
{
public ActionResult Index()
{
return Content("Root -> Admin Controller -> Index action.");
}
}
}
When I run the application, I am expecting to see something interesting, like, may be an exception to the effect, "I can't figure out what route you want."
But when I run the application, it runs just fine and a request for:
/Admin/
yields to the HomeController in the Admin area.
This is because, apparently, and as I recall, the routing mechanism works on a priority basis. It finds the first match and goes with it.
And it is apparently finding that the Admin_default route satisfies the request pattern even before it applies the Default route.
My question(s):
Is my understanding so far correct?
What do I do to play with it? What if I want it to go to the
AdminController in the root area of the application?
Okay, I got the answer after some more thinking. If I just moved the area registration in the global.asax file to after the default route has been registered, it now goes to the AdminController of my root instead of going to the Admin area's HomeController.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// Remove from here
// AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Put here after the default route has been
// registered via the RouteConfig.RegisterRoutes
// call above
AreaRegistration.RegisterAllAreas();
}
}
I have 2 areas Admin and FrontEnd (in that order).
When I am in a view in my FrontEnd area, ActionLink always points to the Admin area:
#Html.ActionLink("Checkout", "Address", "Checkout")
Will be http://localhost:53600/admin/Checkout/Address but the Checkout controller is in my FrontEnd area.
I know I can solve this by specifying a routedata object in the action link and setting area = "FrontEnd" but I don't want to. I want the ActionLink helper to default to my current route.
Is this possible?
All the questions I've read on actionlink are people asking how to link to another area which indicates it defaults to the current area for them. Am I alone with this issue?
Edit, these are my routes which you can see are tied to the correct namespace:
Admin
public void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Administration_default",
"admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", area = "Administration", id = UrlParameter.Optional },
new[] { "CC.Web.Areas.Administration.Controllers" }
);
}
FrontEnd
public void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", area = "FrontEnd", id = UrlParameter.Optional},
new[] {"CC.Web.Areas.FrontEnd.Controllers"}
);
}
Areas should be registered in classes deriving from AreaRegistration overriding the method void RegisterArea(AreaRegistrationContext context), see the msdn.
The AreaRegistrationContext defines its own methods to register area routes that will add the required dataTokens for the areas that are used when generating links and urls:
public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces)
{
if (namespaces == null && Namespaces != null)
{
namespaces = Namespaces.ToArray();
}
Route route = Routes.MapRoute(name, url, defaults, constraints, namespaces);
route.DataTokens[RouteDataTokenKeys.Area] = AreaName;
// disabling the namespace lookup fallback mechanism keeps this areas from accidentally picking up
// controllers belonging to other areas
bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0);
route.DataTokens[RouteDataTokenKeys.UseNamespaceFallback] = useNamespaceFallback;
return route;
}
It also looks like the FrontEnd shouldn't be an area, so you could just have the standard MVC controllers and views (instead of the fronteand area) with an extra Admin area:
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Administration";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Administration_default",
"admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "CC.Web.Areas.Administration.Controllers" }
);
}
}
Remember that you should be calling AreaRegistration.RegisterAllAreas(); at the beggining of your main RegisterRoutes method invoked on app start.
I created an Area in MVC then I created a simple controller and I can't view the Area or any page within that part of my site does anyone know why and how to fix this problem. I created a project a while back with an Area and had no problems, I don't know what has changed or if I had to change something to make it work can somebody please help me out.
Somewhere it's not getting registered.
namespace RedPlanet.Areas.admin.Controllers
{
public class CategoryController : Controller
{
}
}
Area:
public class adminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"admin_default",
"admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
Global ASAX:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<DataContext>());
}
}
You need to specify the namespace when registering the route for your admin area and Main Route in you Application.
Main Route :
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new string[] { "RedPlanet.Controllers" }// specify the namespace
);
In your \Areas\admin\adminAreaRegistration.cs file, you need to modify the RegisterArea() method as follows:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"admin_default",
"admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "RedPlanet.Areas.admin.Controllers" }// specify the namespace
);
}
Update :
if you are using Guid you should change parameter type of your action method to Guid :
public ActionResult Details(Guid guid)
{
//code
return View(model);
}
then create new route for that ;
routes.MapRoute("FooRouteName",
"Controller/Action/{guidParam}",
new { controller = "Category", action = "Index" },
new { guidParam = #"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$" }
);
I have an MVC 4 web application which consists some areas. I have a problem with the routing rules of an area named "Catalog". The RouteConfig.cs file is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
);
}
and Global.asax as follows:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
And CatalogAreaRegistration is something like this:
public class CatalogAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Catalog";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Catalog_default",
"Catalog/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
The problem is when i debug, RouteCollection routes does not include rules that are defined in the area. I used routedebugger and saw that routes collection does not consists rules of "Catalog" area. It has only rules in the RouteConfig.
I have no idea what is the problem. Thanks in advance.
I think due to Visual Studio's caching, some of the dll's aren't compiled properly and this situation can happen. If you do, delete all temp files from following locations:
C:\Temp
C:\Users\%Username%\AppData\Local\Microsoft\VisualStudio
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files
Path\To\Your\Project\obj\Debug
Update :
AppData\Local\Temp\Temporary ASP.NET Files
Then restart the Visual Studio. This is how i resolved.
Just add the namespace of your controllers to the AreaRegistration:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
**namespaces: new string[] { "Web.Admin.Controllers" }**
);
}
I have added a new Area to my MVC3 project and I am trying to link from the _Layout page to the new Area. I have added an Area called 'Admin' that has a controller 'Meets'.
I used the visual studio designer to add the area so it has the correct area registration class etc, and the global.asax file is registering all areas.
However, when I use the following 2 action links in a page in the root, I run into a few problems:
#Html.ActionLink("Admin", "Index", "Meets", new { area = "Admin" }, null)
#Html.ActionLink("Admin", "Index", "Meets", new { area = "" }, null)
When clicking both links, I am taken to the Meets controller in the Admin area, where the application then proceeds to throw an error saying it cannot find the Index page (even though the Index page is present in the Views folder in the Area sub-directory.
The href for the 1st link looks like this:
http://localhost/BCC/Meets?area=Admin
And the href for the 2nd link looks like this:
http://localhost/BCC/Meets
Also if I hit the link that I expect to be created:
http://localhost/BCC/Admin/Meets
I just get a resource cannot be found error. All very perplexing! I hope someone can help...
Strange indeed. Steps that worked perfectly fine for me:
Create a new ASP.NET MVC 3 application using the default Visual Studio template
Add an area called Admin using Visual Studio designer by right clicking on the project
Add new Controller in ~/Areas/Admin/Controllers/MeetsController:
public class MeetsController : Controller
{
public ActionResult Index()
{
return View();
}
}
Add a corresponding view ~/Areas/Admin/Views/Meets/Index.cshtml
In the layout (~/Views/Shared/_Layout.cshtml) add links:
#Html.ActionLink("Admin", "Index", "Meets", new { area = "Admin" }, null)
#Html.ActionLink("Admin", "Index", "Meets", new { area = "" }, null)
Run the application.
Rendered HTML for the anchors:
Admin
Admin
As expected the first link works whereas the second doesn't.
So what's the difference with your setup?
Another option is to utilize RouteLink() instead of ActionLink(), which bypasses the area registrations altogether:
ActionLink version:
Html.ActionLink("Log Off", "LogOff", "Account", new { area = "" }, null)
RouteLink version:
Html.RouteLink("Log Off", "Default",
new { action = "LogOff", controller = "Account" })
The second parameter is a "Route Name" which is registered in Global.asax.cs and in various 'AreaRegistration' subclasses. To use 'RouteLink' to link between different areas, you only need to specify the correct route name.
This following example shows how I would generate three links to different areas from a shared partial, which works correctly regardless of which area I am 'in' (if any):
#Html.RouteLink("Blog", "Blog_default",
new { action = "Index", controller = "Article" })
<br/>
#Html.RouteLink("Downloads", "Download_default",
new { action = "Index", controller = "Download" })
<br/>
#Html.RouteLink("About", "Default",
new { action = "Index", controller = "About" })
Happy coding!
I figured this out - I created a new test project and did exactly the same thing I was doing before and it worked...then after further inspection of all things route-related between the two projects I found a discrepancy.
In the global.asax file in my BCC application, there was a rogue line of code which had inexplicably appeared:
public static void RegisterRoutes(RouteCollection routes)
{
// Problem here
routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
As you can see where my comment is, at some time or other I had placed the routes.Clear() call at the beginning of RegisterRoutes, which meant after I had registered the Areas in Application_Start, I was then immediately clearing what I had just registered.
Thanks for the help...it did ultimately lead to my salvation!
Verify that your AdminAreaRegistration class looks like this:
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
and that you have this in Global.asax.cs:
protected void Application_Start()
{
... // ViewEngine Registration
AreaRegistration.RegisterAllAreas();
... // Other route registration
}
I solved this problem by doing the following.
In my Global.asax.cs, I have
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
}
protected void Application_Start()
{
//Initialise IoC
IoC.Initialise();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
In my PublicAreaRegistration.cs (Public Area), I've got
public class PublicAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Public";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute("Root", "", new { controller = "Home", action = "Index" });
context.MapRoute(
"Public_default",
"Public/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
, new[] { "<Project Namespace here>.Areas.Public.Controllers" }
);
}
}
In my AuthAreaRegistration.cs (Area for Restricted access), I've got
public class AuthAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Auth";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Auth_default",
"Auth/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
And finally, my links in my *.cshtml pages would be like
1) #Html.ActionLink("Log Off", "LogOff", new{area= "Public", controller="Home"})
or
2) #Html.ActionLink("Admin Area", "Index", new {area= "Auth", controller="Home"})
Hope this saves someone hours of research! BTW, I'm talking about MVC3 here.
Kwex.
This might not be the case for most of the developers but I encountered this problem when I added a my first area and did not build my solution. As soon as I build my solution the links started to populate correctly.