Is it possible to put ASP.NET Areas in a class library?
I would like to be able to reuse an area in one of my MVC project in multiple MVC projects. Can I put my area in a class library that can later be reused in a new MVC project?
Thank开发者_StackOverflow中文版s,
Not out of the box. You may take a look at MVCContrib Portable Areas which use a custom VirtualPathProvider allowing you to embed areas as resources into separate assemblies. If you are using ASP.NET MVC 3 you could also take a look at the following blog post.
Be careful though as this might not work if you precompile your web application.
You can have the AreaRegistration
class and the Controllers
in a library. The ASP.NET MVC runtime will register them automatically.
But the the views need to be in any of the following locations:
- ~/Areas/[AreaName]/Views/[ControllerName]/[ViewName].cshtml
- ~/Areas/[AreaName]/Views/Shared/[ViewName].cshtml
- ~/Views/[ControllerName]/[ViewName].cshtml
- ~/Views/Shared/[ViewName].cshtml
Or you can specify them yourself by setting them when registering the View Engine:
var viewEngine = new RazorViewEngine {
AreaViewLocationFormats = new[] { "~/MySharedAreas/{2}/Views/{1}/{0}.cshtml" }
};
2 is area name, 1 is controller name and 0 is action name.
It depends on the purpose. If you just want to reuse the controllers this method will work, but if you want to reuse the Views as well, then you have to go with the solution mentioned by Dimitri
精彩评论