Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces equivalent in ASP.NET MVC?

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?

like image 978
Gotjosh Avatar asked Nov 25 '25 21:11

Gotjosh


1 Answers

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:

like image 67
gideon Avatar answered Nov 28 '25 09:11

gideon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!