Asp.net MVC (一) 入门

先在 vs08 中 创建了一个 MVC 项目, 然后 习惯性的设置了起始页。

于是问题出现了。 取消起始页后正常。 那肯定有映射之类的玩意儿

 

查了查。 原来在Global.asax 里面

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas(); //注册 ASP.NET MVC 应用程序中的所有区域。 link //不知道里面做了什么
            RegisterRoutes(RouteTable.Routes); //注册路径
        }

下面就是访问的规则了

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // 这是一个约束。
            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = "" }, // 参数默认值
          new { id = @"[\d]*" } //id必须为数字 还可以加上约束         }
); }

可是我们如何修改这些规则呢?

http://localhost:14593/Home/About

 同样 传参数 也有 http://localhost:14593/Prdt/About/1

类似于 /Prdt/About.aspx?id=1

可是很多时候 我们不仅仅是要传入 ID , 比如

http://localhost:14593/Prdt/About/1111/22222

http://localhost:14593/Blogs/Archive/[Year]/[Month]/[Day]

这个时候怎么办呢?

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{Year}/{Month}/{Day}", // 带有参数的 URL
                new { controller = "Blogs", action = "Archive", Year = "2008", Month = "", Day = "" } // 参数默认值
            );            
}

 

然后 在目录里 创建以下文件

最后在 Controllers 里创建 Archive 想对应的视图文件

        public ActionResult Archive(int year)
        {
            ViewData["Message"] = year;
            return View();
        }

 

PS: 我曾今尝试过 使用string 作为参数。 他还是传过来了。 不知道里面解析时候 做了什么。 太智能也让人不放心啊

于是这样就传过来了 我们想要的参数。

 

这样基本实现了大部分要求

于是 这就有一个问题了。

http://localhost:14593/Blogs/Archive/[Year]/[Month]/[Day]

http://localhost:14593/Game/[ID]

比如想同时两个规则。 于是我尝试了一下

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "normal", // 路由名称
                "{controller}/{action}", // 带有参数的 URL
                new { controller = "Home", action = "Index" } // 参数默认值
                );
            routes.MapRoute(
                "Blogs", // 路由名称
                "{controller}/{action}/{Year}/{Month}/{Day}", // 带有参数的 URL
                new { controller = "Blogs", action = "Archive", Year = "2008", Month = "", Day = "" } // 参数默认值
            );
            
        }

 

于是正常访问。

访问blogs

Ok 正常了。

还是没有具体找到处理解析这玩意儿的地方。 留个坑吧

 

其实在前文中已经提到了 其实就是在 Controller

对应 视图中建立相应的类

对应。

 

return View(); 返回当前视图。 当然你也可以手动去写好

        public ActionResult About()
        {
            //return View();
            ViewData["Message"] = "欢迎使用 ASP.NET MVC_About!";
            return View("index");
        }

 

 大概分层就是这样

是不是有点儿像三层。

下图是 web Form vs mvc

 

to be continue..

posted @ 2012-05-18 22:52  CallMeTommy  阅读(302)  评论(0编辑  收藏  举报