Namespaces equivalent in ASP.NET MVC?

*爱你&永不变心* 提交于 2019-12-10 10:28:28

问题


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?


回答1:


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:




回答2:


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.



来源:https://stackoverflow.com/questions/5343053/namespaces-equivalent-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!