MVC 多级文件夹问题,关于asp.net mvc2.0的Areas的应用
时间:2010-11-08 来源:深邃老马
问题:
有个项目需要到:1、用户管理后台、2、开发人员后台、3用户前台
拿其中的文章列表这模块来举例
预计访问路径:1、用户管理后台:http://demo.com/admin/News/index
2、开发人员后台:http://demo.com/s7mmer/News/index
3、用户前台:http://demo.com/News/index
使用asp.net mvc1.0做这个是非常麻烦的事情,网上查了下,发现asp.net mvc2.0提供了Areas特性
解决:
网上查了下用法,上面说给项目添加一个名字为Admin的areas,打开VS右键项目或者文件夹都找不到areas这个选项,不知道是我理解错误还是补丁没装好?
于是只能采取如下步骤:
1、在根目录下新建个Areas文件夹的
2、在Areas 中手动建目录如下
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace S7mmer.Web
{
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get { return "Admin"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
//匹配规则可以自己修改
context.MapRoute(
"AdminController_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
new string[] { "S7mmer.Web.Areas.Admin.Controllers" }//controllers的命名空间
);
}
}
public class S7mmerAreaRegistration : AreaRegistration
{
public override string AreaName
{
get { return "S7mmer"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
//匹配规则可以自己修改
context.MapRoute(
"S7mmerController_default",
"S7mmer/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
new string[] { "S7mmer.Web.Areas.S7mmer.Controllers" }//controllers的命名空间
);
}
}
public class WebSiteAreaRegistration : AreaRegistration
{
public override string AreaName
{
get { return "WebSite"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
//匹配规则可以自己修改
context.MapRoute(
"WebSiteController_default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
new string[] { "S7mmer.Web.Areas.WebSite.Controllers" }//controllers的命名空间
);
}
}
}
4、在Areas文件夹下的Admin文件夹下新建一个NewsController.cs
5、在NewsController.cs中的public ActionResult Index()中右键添加view,发现在
已经在news中添加了index.aspx
6、修改根目录下的Global.asax文件,在Application_Start()里面添加AreaRegistration.RegisterAllAreas();
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// RegisterRoutes(RouteTable.Routes);
}
编译、访问 http://localhost:1108/admin/News/index,用户管理后台访问成功!
其他按照上面的步骤来就可以达到了效果,这样子可以实现前后台文件的分离,方便管理
《逆水行舟,不进则退》