3

In rails I could create a namespace in order to encapsulate views inside a given name ( or URL prefix)

What I want to do is create a namespace (or Area I believe? ) that shall encapsulate all the administrator controllers inside a given name.

For example, I want to create an Admin namespace, where whenever I go to www.myapp.com/admin/ it would get the me the controller admin with the index method, and that whenever I go to www.myapp.com/admin/products it shall call the product controller with the index method and so on because i also want to limit these controllers to a person that must be logged in as in.

URL and routing wise, how can I accomplish the mentioned before?

2 Answers 2

4

The feature infact is called Areas in asp.net mvc.

You right-click your project in Visual Studio and click add Area.

You'll now have a sub folder with folders for Views, Controllers and a Shared folder. Also a route is added to the project.

Snag: There is a case where it would cause a problem if you have a HomeController inside one of your areas as it will conflict with the HomeController route for the website root. Steven Sanderson has fix for this in his book:

Change your default route to this:

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", // Parameter defaults
id = UrlParameter.Optional },
new [] { "MyAppName.Controllers" } // Prioritized namespace
);

See MDSN Articles.

Video on Asp.net Areas.

Good article by Steven Sanderson:

Sign up to request clarification or add additional context in comments.

2 Comments

I have one more question though. Would I have to remake my models/controllers or can't I just use the same ones I have in my root application? I'd like my app to stay as DRY as possible.
You do have to define new controllers under each area. Maybe you could write base controllers and derive from them appropriately. For models, its up to you. You can place models specific to an area within the area folder (which in turn puts in in a different namespace) or you can place common models in the root Model folder and use them from anywhere.
0

The library MvcCodeRouting allows you to organize controllers, views and URLs using namespace hierarchies, it reflects on your controllers and automatically creates the routes for them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.