22
ASP.NET MVC ASP.NET MVC 培培 培培 深深深深深深深深深深深深深深 Daniel Chow http://www.cnblogs.com/ DanielChow

Asp.net mvc 培训

Embed Size (px)

DESCRIPTION

ASP.NET MVC 培训

Citation preview

Page 1: Asp.net mvc 培训

ASP.NET MVC ASP.NET MVC 培训培训

深圳市国泰安信息技术有限公司

Daniel Chow

http://www.cnblogs.com/DanielChow

Page 2: Asp.net mvc 培训

ASP.NET MVC 的基本概念

提 纲

基础介绍 HtmlHelper ,UrlHelper, Filter

Url Routing and Test Tool

Data Annotations and Validation

Controller 和 View 之间的数据传输

ASP.NET MVC 生命周期

AJAX & Unobtrusive Javascript

问答 (QA)

Page 3: Asp.net mvc 培训

ASP.NET MVC 的基本概念

MVC ( Model-View-Controller ,模型—视图—控制器模式)用于表示一种软件架构模式。它把软件系统分为三个基本部分:模型( Model ),视图( View )和控制器( Controller )。

MVC 本身是一种模式 , 它的核心思想是:把一个应用的输入、处理、输出流程按照Model 、 View 、 Controller 的方式进行分离我们今天讨论的 ASP.NET MVC , 是微软的一个开源产品 , 后续的讨论基于 ASP.NET MVC 3.0版本 . 在 ASP.NET MVC 中的 MVC ,我的理解是一种表现层的 MVC 模式 , 也就是传统三层架构的 UI 层 .

Page 4: Asp.net mvc 培训

• Model , 这里是 View Model 和三层中的 Domain Model 区分开来 , 它给 View 提供数据,还提供其它一些特性 , 用来支持 Data Annotations and Validation(后面会讨论 ) , 当然这一层背后应该数据业务层的支持

• Controller , 处理用户请求 / 操作和输出响应 ,( 接收客户端的输入数据 , 相应的数据过滤 , 控制视图的显示 )这一层的独立具有很多意义 , 和传统的 WebForm 相比它不依赖与 View, 也就支持 Test-Driven Development 了。

• View , 显示数据和用来做用户操作 UI 的,它的显示是由Controller 来控制的 .

Page 5: Asp.net mvc 培训
Page 6: Asp.net mvc 培训

ASP.NET MVC 生命周期

Page 7: Asp.net mvc 培训
Page 8: Asp.net mvc 培训
Page 9: Asp.net mvc 培训

基础介绍

• Demo1 演示1 、有两个视图引擎 ASPX 和 Razor , 他们的区别在于 View 层的 Server side 代码写法不同, Razor 的写法更简洁和优雅,然后为了区分开他们的文件扩展名不同 .2 、自定义 HtmlHelper:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.WebPages.Html;

namespace System.Web.Mvc{ public static class HtmlHelperExtensions { public static string StyleText(this HtmlHelper htmlHelper, string text ,string styleName) { return string.Format("<span class='{1}'>{0}</span>", text, styleName); } }}

Page 10: Asp.net mvc 培训

• 4 中基本 Filter 类型 IActionFilter, IAuthorizationFilter, IResultFilter, IExceptionFilter

他们的执行顺序请看 Demo

Page 11: Asp.net mvc 培训

Controller 和 View 之间的数据传输

与传统 WebForm 差别较大 , 从生命周期图上就可以看出

ASP.NET MVC 提供两种传值方法:

1 、 TempData[“Test”] 一次性的只能传递到下一个 View

2 、 ViewData[“Test”]

3 、 ViewBag.Test 等价于 2 , 写法不同而已 , 看起来是强类型,其实是动态类型

Controller:

ViewData["Test"] = DateTime.Now.ToString();TempData["TempTest"] = DateTime.Now.ToString();ViewBag.TestBag = DateTime.Now.ToString();

View(Razor):

@ViewData["Test"]<br />@TempData["TempTest"]<br />@ViewBag.TestBag<br />

Page 12: Asp.net mvc 培训

Data Annotations and Validation

• Demo

Page 13: Asp.net mvc 培训

AJAX & Unobtrusive Javascript

当打开 ClientValidationEnabled 之后,会自动产生客户端验证代码 :产生的代码分两种:1 、基于 MicrosoftAjax 的,会在页面中产生相应的验证脚本2 、基于 Jquery 的 Unobtrusive Script 方式进行验证 , 需要打开UnobtrusiveJavaScriptEnabled

验证的依据就是 View Model 上定义的约束 . 上一节提到的。

当然你还可以自己手写脚本进行验证。

Jquery AJAX 和 Controller 交付 :Controller:

public ActionResult GetVersion() { var version = new { Main = 6 , Second = 4, Fix = 3, Build = 235 };

return Json(version);//,JsonRequestBehavior.AllowGet); }

Page 14: Asp.net mvc 培训

• <div id="footer“>Demo Version:<span id="version"></span></div><script type="text/javascript">

• String.prototype.JsonFormat = function (config, reserve) { return this.replace(/\{([^}]*)\}/g, (typeof config == 'object') ? function (m, i) { var ret = config[i]; return ret == null && reserve ? m : ret } : config); };

• $(function () {

• $.ajax({

• type: "POST",

• url: '/Public/GetVersion',

• //data: {},

• dataType: "json",

• cache: true,

• success: function (data) {

• $("#version").text("{Main}.{Second}.{Fix}.{Build}".JsonFormat(data));

• },

• error: function (XMLHttpRequest, textStatus, errorThrown) {

• $("#version").text("0.0.0.0");

• }

• });

• });

• </script>

Page 15: Asp.net mvc 培训

Url Routing and Test Tool

• 首页地址是 : localhost/home/index• 我们发现访问上面的地址 , 最后会传递给 HomeController 中名为 index 的 action( 即 HomeController 类中的

index 方法 ).• 在 global.asax 中 :

protected void Application_Start() { AreaRegistration.RegisterAllAreas();// 注册所有的域 RegisterGlobalFilters(GlobalFilters.Filters);// 注册全局的 fileter RegisterRoutes(RouteTable.Routes);// 注册路由规则 //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);// 路由调试工具}

protected void Application_Start() { AreaRegistration.RegisterAllAreas();// 注册所有的域 RegisterGlobalFilters(GlobalFilters.Filters);// 注册全局的 fileter RegisterRoutes(RouteTable.Routes);// 注册路由规则 //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);// 路由调试工具}public static void RegisterRoutes(RouteCollection routes){ routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRouteMapRoute( "Default", // 路由名称 "{controller}/{action}/{id}", // 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数

默认值);

}

public static void RegisterRoutes(RouteCollection routes){ routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRouteMapRoute( "Default", // 路由名称 "{controller}/{action}/{id}", // 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数

默认值);

}

Page 16: Asp.net mvc 培训

MapRoute( string name, string url);MapRoute( string name, string url, object defaults);MapRoute( string name, string url, string[] namespaces);MapRoute( string name, string url, object defaults, object constraints);MapRoute( string name, string url, object defaults, string[] namespaces);MapRoute( string name, string url, object defaults, object constraints, string[] namespaces);

MapRoute( string name, string url);MapRoute( string name, string url, object defaults);MapRoute( string name, string url, string[] namespaces);MapRoute( string name, string url, object defaults, object constraints);MapRoute( string name, string url, object defaults, string[] namespaces);MapRoute( string name, string url, object defaults, object constraints, string[] namespaces);

defaults 参数 :   url 参数的默认值 . 如果一个 url 只有 controller: localhost/home/  而且我们只建立了一条 url 获取数据规则 : {controller}/{action}  那么这时就会为 action 参数设置 defaults 参数中规定的默认值 . defaults 参数是 Object 类型 , 所以可以传递一个匿名类型来初始化默认值 :new { controller = "Home", action = "Index" }  实例中使用的是三个参数的 MapRoute 方法 :       routes.MapRoute(        “ Default”,                               “ {controller}/{action}/{id}”,                        new { controller = “ Home”, action = “ Index”, id = “” }        );

defaults 参数 :   url 参数的默认值 . 如果一个 url 只有 controller: localhost/home/  而且我们只建立了一条 url 获取数据规则 : {controller}/{action}  那么这时就会为 action 参数设置 defaults 参数中规定的默认值 . defaults 参数是 Object 类型 , 所以可以传递一个匿名类型来初始化默认值 :new { controller = "Home", action = "Index" }  实例中使用的是三个参数的 MapRoute 方法 :       routes.MapRoute(        “ Default”,                               “ {controller}/{action}/{id}”,                        new { controller = “ Home”, action = “ Index”, id = “” }        );

Page 17: Asp.net mvc 培训

constraints 参数 :  用来限定每个参数的规则或 Http 请求的类型 .constraints属性是一个 RouteValueDictionary对象 ,也就是一个字典表 , 但是这个字典表的值可以有两种 :  用于定义正则表达式的字符串。正则表达式不区分大小写。  一个用于实现 IRouteConstraint 接口且包含 Match 方法的对象。  通过使用正则表达式可以规定参数格式 , 比如 controller 参数只能为 4 位数字 :new { controller = @"\d{4}"}

   通过第 IRouteConstraint 接口目前可以限制请求的类型 .因为 System.Web.Routing 中提供了HttpMethodConstraint 类 , 这个类实现了 IRouteConstraint 接口 . 我们可以通过为RouteValueDictionary字典对象添加键为 "httpMethod", 值为一个 HttpMethodConstraint对象来为路由规则添加 HTTP 谓词的限制 , 比如限制一条路由规则只能处理 GET 请求 :httpMethod = new HttpMethodConstraint( "GET", "POST" )

  完整的代码如下 :       routes.MapRoute(        “ Default”,                                “ {controller}/{action}/{id}”,                        new { controller = “ Home”, action = “ Index”, id = “” },          new { controller = @“\d{4}" , httpMethod = new ttpMethodConstraint( "GET", "POST" ) }       );

constraints 参数 :  用来限定每个参数的规则或 Http 请求的类型 .constraints属性是一个 RouteValueDictionary对象 ,也就是一个字典表 , 但是这个字典表的值可以有两种 :  用于定义正则表达式的字符串。正则表达式不区分大小写。  一个用于实现 IRouteConstraint 接口且包含 Match 方法的对象。  通过使用正则表达式可以规定参数格式 , 比如 controller 参数只能为 4 位数字 :new { controller = @"\d{4}"}

   通过第 IRouteConstraint 接口目前可以限制请求的类型 .因为 System.Web.Routing 中提供了HttpMethodConstraint 类 , 这个类实现了 IRouteConstraint 接口 . 我们可以通过为RouteValueDictionary字典对象添加键为 "httpMethod", 值为一个 HttpMethodConstraint对象来为路由规则添加 HTTP 谓词的限制 , 比如限制一条路由规则只能处理 GET 请求 :httpMethod = new HttpMethodConstraint( "GET", "POST" )

  完整的代码如下 :       routes.MapRoute(        “ Default”,                                “ {controller}/{action}/{id}”,                        new { controller = “ Home”, action = “ Index”, id = “” },          new { controller = @“\d{4}" , httpMethod = new ttpMethodConstraint( "GET", "POST" ) }       );

Page 18: Asp.net mvc 培训

路由规则多了之后很容易造成混淆,如何知道是被那一条路由规则被执行了呢?这里介绍一个路由调试工具: RouteDebug使用很简单,添加引用然后 , Application_Start 中追加一行代码:

RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);// 路由调试工具效果如下:RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);// 路由调试工具效果如下:

Page 19: Asp.net mvc 培训
Page 20: Asp.net mvc 培训

• Area( 域 )• Area 是从 MVC 2 开始引入的,它的作用 :

• 允许你从功能层面拆分 Models,Views,Controllers, 进一步体现模块化的思想,有助于大项目的管理

• Demo 演示

• 路由规则注意事项:

1. 要明确间隔符 eg: {controller}/{action}/{id} , {controller}{action}{id}

2. 尽量明确参数类型 , 加上参数约束3. 路由注册是有顺序的 . 一般来说路由规则范围越小越精确的越靠前,越通用越靠后。4. 添加 Area 之后很可能会引起 Area Routing 冲突,如果外面有 Home/index 域里面也有 Home/index

这个时候需要在路由注册时加上名词空间加以区别 .

Page 21: Asp.net mvc 培训

问答 (QA)& 资料推荐

• ASP.NET MVC CodePlex 地址 http://aspnet.codeplex.com/wikipage?title=MVC&referringTitle=Home

• 入门与实战推荐学习项目 Nerd Dinner , 有兴趣深入研究推荐学习MvcContrib 、 Orchard 等项目

Page 22: Asp.net mvc 培训