以前一直对.Net的表现业务感觉不爽,上次和Forever讨论很久,也没能很好的解决表现成业务分离的问题,最近看到了新的Asp.Net MVC框架,恍然茅塞顿开,原来如此,以前的WebForm基于MVP方式,这次新的MVC框架将表现成很轻松的分离这些业务.
Ok,今天我就来试着用MVC的方式写一个小的Demo程序,这个程序非常简单,就是一个Article的发布和浏览程序,程序有两个表,分别是category和content,分别是分类表,文章表,程序使用MySql数据库,建表脚本如下:
create table `category`(
`id` int primary key not null auto_increment,
`name` varchar(255) not null,
`intro` varchar(1024),
`order` int default 1000,
`url` varchar(255),
`isurl` bit not null default 0
);
ALTER TABLE `category` ADD INDEX ( `order` ) ;
create table `content`(
`id` int primary key not null auto_increment,
`categoryid` int not null,
`title` varchar(255) not null,
`info` varchar(1024),
`content` text,
`posttime` datetime not null,
`postuser` varchar(50),
`hits` int not null default 0
);
ALTER TABLE `content` ADD INDEX ( `categoryid` ) ;
ALTER TABLE `content` ADD INDEX ( `postuser` ) ;
ALTER TABLE `content` ADD INDEX ( `hits` ) ;
insert into `category`(`name`,`intro`,`order`,`url`,`isurl`) values
(''Index'',''Index Page'',0,''/default.aspx'',1),
(''News'',''业界新闻'',1,'''',0),
(''.Net'',''.Net开发'',2,'''',0),
(''Asp.Net MVC'',''Asp.Net MVC'',3,'''',0),
(''C/C++'',''C/C++开发'',4,'''',0);
insert into `content`(`categoryid`,`title`,`info`,`content`,`posttime`,`postuser`,`hits`) values
(2,''MvcArticle System 1.0发布'',''MvcArticle System 1.0发布'',''经过一段时间的开发,MvcArticle System 1.0发布终于发布.'',NOW(),''Leven'',0);
在程序中,我创建一个HttpModule来初始化整个UrlRouting部分.UrlRouting初始化代码如下:
private static void InitRoutingUrls(RouteCollection routes)
{
routes.Add(new Route(string.Format("article{0}/list/{{category}}/{{page}}", WebConfig.MvcHandle), new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "article", action = "list", category = "0", page = "1" }),
Constraints = new RouteValueDictionary(new { category = "\\d+", page = "\\d+" }),
});
routes.Add(new Route(string.Format("article{0}/index/{{page}}", WebConfig.MvcHandle), new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "article", action = "index", page = "1" }),
Constraints = new RouteValueDictionary(new { page = "\\d+" }),
});
routes.Add(new Route(string.Format("article{0}/view/{{id}}", WebConfig.MvcHandle), new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "article", action = "view", id = "1" }),
Constraints = new RouteValueDictionary(new { id = "\\d+" }),
});
routes.Add(new Route(string.Format("article{0}/add", WebConfig.MvcHandle), new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "article", action = "add" }),
});
routes.Add(new Route(string.Form