再接再厉VS 2008 sp1 + .NET 3.5 sp1(8) - Dynamic Data(动态数据)

简介:
再接再厉VS 2008 sp1 + .NET 3.5 sp1(8) - Dynamic Data(动态数据)


作者: webabcd


介绍
以Northwind为示例数据库,演示Dynamic Data(动态数据)
  • MetaModel - 数据库和域对象之间的映射的抽象
  • MetaModel.RegisterContext() - 使用指定的配置上下文注册指定的数据上下文
  • Scaffold - 译为基架。即基于数据库架构(linq to sql 或 entity framework)生成网页模板的机制
  • ScaffoldTableAttribute(false) - 隐藏指定的表
  • ScaffoldColumn(false) - 隐藏指定的字段
  • MetadataTypeAttribute(Type metadataClassType) - 指定要与数据模型类关联的元数据类
  • DynamicField - 显示指定的动态数据字段,相当于 BoundField
  • DynamicControl - 通过指定的字段模板显示指定的动态数据字段


示例
全局配置
Global.asax
<%@ Application Language= "C#" %> 
<%@ Import Namespace= "System.Web.Routing" %> 
<%@ Import Namespace= "System.Web.DynamicData" %> 

<script runat= "server"
         
static void RegisterRoutes() static void RegisterRoutes(RouteCollection routes) 
        { 
                MetaModel model =  new MetaModel(); 

                // MetaModel - 数据库和域对象之间的映射的抽象 
                // MetaModel.RegisterContext(Type contextType, ContextConfiguration configuration) - 使用指定的配置上下文注册指定的数据上下文 
                //         contextType - 数据模型中所定义的数据上下文类型 
                //         configuration - 相关的配置。其 ScaffoldAllTables 属性为是否要启用基架,基架就是基于数据库架构(linq  to sql 或 entity framework)生成网页模板的机制 
                model.RegisterContext(typeof(VS2008SP1.Business.NorthwindEntities),  new ContextConfiguration() { ScaffoldAllTables =  true }); 

                // 下面的语句支持分页模式,在这种模式下,“列表”、“详细”、“插入” 
                // 和“更新”任务是使用不同页执行的。若要启用此模式,请取消注释下面 
                // 的 route 定义,并注释掉后面的合并页模式部分中的 route 定义。 
                routes.Add( new DynamicDataRoute( "{table}/{action}.aspx"
                { 
                        Constraints =  new RouteValueDictionary( new { action =  "List|Details|Edit|Insert" }), 
                        Model = model 
                }); 

                // 下面的语句支持合并页模式,在这种模式下,“列表”、“详细”、“插入” 
                // 和“更新”任务是使用同一页执行的。若要启用此模式,请取消注释下面 
                // 的 routes,并注释掉上面的分页模式部分中的 route 定义。 
                // routes.Add( new DynamicDataRoute( "{table}/ListDetails.aspx") { 
                //         Action = PageAction.List, 
                //         ViewName =  "ListDetails"
                //         Model = model 
                // }); 

                // routes.Add( new DynamicDataRoute( "{table}/ListDetails.aspx") { 
                //         Action = PageAction.Details, 
                //         ViewName =  "ListDetails"
                //         Model = model 
                // }); 
        } 

        void Application_Start(object sender, EventArgs e) 
        { 
                RegisterRoutes(RouteTable.Routes); 
        } 

</script>
 
 
1、数据驱动的 Web 应用程序
详见源代码中的DynamicDataSite项目。动态数据的目录结构详见MSDN
Scaffold.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

using System.ComponentModel.DataAnnotations; 
using System.ComponentModel; 

namespace VS2008SP1.Business 

        /**//* 
         * Scaffold - 译为基架。即基于数据库架构(linq  to sql 或 entity framework)生成网页模板的机制 
         * ScaffoldTableAttribute( false) - 隐藏指定的表 
         * ScaffoldColumn( false) - 隐藏指定的字段 
         * MetadataTypeAttribute(Type metadataClassType) - 指定要与数据模型类关联的元数据类 
         */ 

        [ScaffoldTable( false)] 
         public partial  class Region 
        { 
                // Region 表不会被路由(显示) 
        } 

        [MetadataType(typeof(Customers_Metadata))] 
         public partial  class Customers 
        { 
                // 将 Customers 的元数据关联到 Customers_Metadata 
        } 

         public  class Customers_Metadata 
        { 
                [ScaffoldColumn( false)] 
                 public object Phone; 

                // Phone 不会在 Customers 表中被显示 
        } 
}
 
Validation.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

using System.ComponentModel.DataAnnotations; 
using System.ComponentModel; 

namespace VS2008SP1.Business 

        [MetadataType(typeof(Products_Metadata))] 
         public partial  class Products 
        { 
                // entity framework 会自动生成类似 OnFieldChanging() 的部分方法 
                // 如果想做字段的自定义输入验证,则可以重写此方法 
                partial void OnUnitPriceChanging(global::System.Nullable<decimal> value) 
                { 
                         if (value > 1000) 
                        { 
                                throw  new ValidationException( "UnitPrice 不能大于 1000"); 
                        } 
                } 
        } 

         public  class Products_Metadata 
        { 
                // [DataType(DataType.EmailAddress)] // 指定要与数据字段关联的附加类型的名称 
                // [DisplayFormat()] // 格式化输出 
                // [Range()] // 指定字段的范围约束 
                // [RegularExpression()] // 正则表达式验证 
                // [StringLength()] // 字段的字符长度验证 
                [Required()] // 必填 
                [UIHint( "MyDecimal")] // 使用名为 MyDecimal 的字段模板 
                 public object UnitPrice; 

                [DisplayName( "产品名称")] // 指定的字段所显示的名称。在动态数据中,查看 Products 表,其 header 将显示为 产品名称 
                [StartsWith( "webabcd", ErrorMessage =  "{0} 必须以 {1} 开头")] // 应用自定义 ValidationAttribute 
                 public object ProductName {  getset; } 

        } 


        // 编写一个自定义 ValidationAttribute,验证指定字段是否是以指定的字符串开头 
        [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple =  false)] 
        sealed  public  class StartsWithAttribute : ValidationAttribute 
        { 
                readonly  string _param; 

                /**//// <summary> 
                /// 构造函数 
                /// </summary> 
                /// <param name= "param">指定的开头字符串</param> 
StartsWithAttribute() StartsWithAttribute( string param) 
                { 
                        _param = param; 
                } 

                /**//// <summary> 
                /// 是否通过验证 
                /// </summary> 
                /// <param name= "value">输入值</param> 
                /// <returns></returns> 
override bool IsValid() override bool IsValid(object value) 
                { 
                        return (( string)value).ToLower().StartsWith(this._param.ToLower()); 
                } 

                /**//// <summary> 
                /// 格式化错误信息 
                /// </summary> 
                /// <param name= "name">指定的字段名</param> 
                /// <returns></returns> 
override  string FormatErrorMessage() override  string FormatErrorMessage( string name) 
                { 
                        return  string.Format(ErrorMessageString, name, this._param); 
                } 
        } 

 
 
2、以 Products 表为例,演示动态数据的应用
MyProducts.aspx
<%@ Page Language= "C#" MasterPageFile= "~/Site.master" CodeFile= "MyProducts.aspx.cs" 
         Inherits= "MyProducts" Title= "以 Products 表为例,演示动态数据的应用" %> 

<%@ Register Assembly= "System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
        Namespace= "System.Web.UI.WebControls" TagPrefix= "asp" %> 
<asp:Content ID= "Content1" ContentPlaceHolderID= "ContentPlaceHolder1" runat= "Server"
        <asp:DynamicDataManager ID= "DynamicDataManager1" runat= "server" AutoLoadForeignKeys= "true" /> 
        <h2> 
                以 Products 表为例,演示动态数据的应用</h2> 
        <asp:FormView ID= "FormView1" runat= "server" DataSourceID= "FormDataSource" AllowPaging= "True" 
                DataKeyNames= "ProductId"
                <ItemTemplate> 
                        <table> 
                                <tr> 
                                        <td> 
                                                ProductId: 
                                        </td> 
                                        <td> 
                                                <!--DynamicField - 显示指定的动态数据字段,相当于 BoundField--> 
                                                <!--DynamicControl - 通过指定的字段模板显示指定的动态数据字段--> 
                                                <asp:DynamicControl ID= "ProductId" runat= "server" DataField= "ProductId" /> 
                                        </td> 
                                </tr> 
                                <tr> 
                                        <td> 
                                                ProductName: 
                                        </td> 
                                        <td> 
                                                <asp:DynamicControl ID= "ProductName" runat= "server" DataField= "ProductName" /> 
                                        </td> 
                                </tr> 
                                <tr> 
                                        <td> 
                                                UnitPrice: 
                                        </td> 
                                        <td> 
                                                <asp:DynamicControl ID= "UnitPrice" runat= "server" DataField= "UnitPrice" /> 
                                        </td> 
                                </tr> 
                                <tr> 
                                        <td colspan= "2"
                                                <asp:LinkButton ID= "InsertButton" runat= "server" CommandName= "New" CausesValidation= "false" 
                                                        Text= "New" /> 
                                                <asp:LinkButton ID= "EditButton" runat= "server" CommandName= "Edit" CausesValidation= "false" 
                                                        Text= "Edit" /> 
                                                <asp:LinkButton ID= "DeleteButton" runat= "server" CommandName= "Delete" CausesValidation= "false" 
                                                        Text= "Delete" /> 
                                        </td> 
                                </tr> 
                        </table> 
                </ItemTemplate> 
                <EditItemTemplate> 
                        <table> 
                                <tr> 
                                        <td> 
                                                ProductId: 
                                        </td> 
                                        <td> 
                                                <asp:DynamicControl ID= "ProductId" runat= "server" DataField= "ProductId" Mode= "ReadOnly" /> 
                                        </td> 
                                </tr> 
                                <tr> 
                                        <td> 
                                                ProductName: 
                                        </td> 
                                        <td> 
                                                <!-- 
                                                        UIHint - 指定字段模板,此例的字段模板会以黄色背景显示数据 
                                                        Mode - 设置呈现模式 [System.Web.UI.WebControls.DataBoundControlMode 枚举]    
                                                                DataBoundControlMode.ReadOnly - 只读模式。默认值 
                                                                DataBoundControlMode.Edit - 编辑模式 
                                                                DataBoundControlMode.Insert - 插入模式 
                                                --> 
                                                <asp:DynamicControl ID= "ProductName" runat= "server" DataField= "ProductName" Mode= "Edit" 
                                                        UIHint= "YelloText" /> 
                                        </td> 
                                </tr> 
                                <tr> 
                                        <td> 
                                                UnitPrice: 
                                        </td> 
                                        <td> 
                                                <asp:DynamicControl ID= "UnitPrice" runat= "server" DataField= "UnitPrice" Mode= "Edit" /> 
                                        </td> 
                                </tr> 
                                <tr> 
                                        <td colspan= "2"
                                                <asp:LinkButton ID= "UpdateButton" runat= "server" CommandName= "Update">Update</asp:LinkButton> 
                                                <asp:LinkButton ID= "CancelEditButton" runat= "server" CommandName= "Cancel" CausesValidation= "false">Cancel</asp:LinkButton> 
                                        </td> 
                                </tr> 
                        </table> 
                </EditItemTemplate> 
                <InsertItemTemplate> 
                        <table> 
                                <tr> 
                                        <td> 
                                                ProductName: 
                                        </td> 
                                        <td> 
                                                <asp:DynamicControl ID= "ProductName" runat= "server" DataField= "ProductName" Mode= "Insert" /> 
                                        </td> 
                                </tr> 
                                <tr> 
                                        <td colspan= "2"
                                                <asp:LinkButton ID= "InsertButton" runat= "server" CommandName= "Insert" Text= "Insert" /> 
                                                <asp:LinkButton ID= "CancelInsertButton" runat= "server" CommandName= "Cancel" CausesValidation= "false" 
                                                        Text= "Cancel" /> 
                                        </td> 
                                </tr> 
                        </table> 
                </InsertItemTemplate> 
                <PagerSettings Position= "Bottom" Mode= "NumericFirstLast" /> 
        </asp:FormView> 
        <asp:EntityDataSource ID= "FormDataSource" runat= "server" ConnectionString= "name=NorthwindEntities" 
                DefaultContainerName= "NorthwindEntities" EntitySetName= "Products" ContextTypeName= "VS2008SP1.Business.NorthwindEntities" 
                EnableInsert= "True" EnableUpdate= "True" EnableDelete= "True"
        </asp:EntityDataSource> 
</asp:Content>
 
 




     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/341156 ,如需转载请自行联系原作者

相关文章
|
30天前
mvc.net分页查询案例——DLL数据访问层(HouseDLL.cs)
mvc.net分页查询案例——DLL数据访问层(HouseDLL.cs)
8 0
|
6月前
|
关系型数据库 MySQL 数据库
找不到请求的 .Net Framework Data Provider。可能没有安装
做的一个项目,框架为.net framework 数据库为mysql 出现如标题错误 检查是否安装mysql、是否安装mysql connector net 笔者是因为没有安装后者mysql connector net 下载地址: [mysql connector net](https://downloads.mysql.com/archives/c-net/ "mysql connector net") 笔者安装截图如下: ![请在此添加图片描述](https://developer-private-1258344699.cos.ap-guangzhou.myqcloud.com/c
56 0
|
29天前
|
SQL 数据库
使用ADO.NET查询和操作数据
使用ADO.NET查询和操作数据
9 0
|
2月前
|
SQL 开发框架 .NET
ASP.NET WEB+EntityFramework数据持久化——考核练习库——1、用户管理系统(考点:查询列表、增加、删除)
ASP.NET WEB+EntityFramework数据持久化——考核练习库——1、用户管理系统(考点:查询列表、增加、删除)
67 0
|
4月前
|
Oracle 关系型数据库 数据管理
.NET医院检验系统LIS源码,使用了oracle数据库,保证数据的隔离和安全性
LIS系统实现了实验室人力资源管理、标本管理、日常事务管理、网络管理、检验数据管理(采集、传输、处理、输出、发布)、报表管理过程的自动化,使实验室的操作人员和管理者从繁杂的手工劳作中解放出来,提高了检验人员的工作效率和效益,降低了劳动成本和差错发生率。
|
6月前
|
前端开发 JavaScript
.net core 前端传递参数有值 后端接收到的数据却是null
1、问题分析 在做接口测试时,偶然出现了前端输出有值,但是后端断点调试时却出现接收参数总是为null的情况 2、解决办法 前端打印log,看前端的每一个传值的数据类型,与后端请求参数类进行认真的一一比对 小技巧: ① 直接打印调用接口的传参值的数据类型,例如 console.log(type of this.form.name) --string console.log(type of this.form.age) --number 打印的数据类型与后端接口的参数类比对,查出不对应的类型 ② 关于非必填的值,默认传值可能出现空字符串(' ')、NaN值(Not a Number
99 0
|
7月前
|
JSON 数据格式
.NET Core - 配置绑定:使用强类型对象承载配置数据
.NET Core - 配置绑定:使用强类型对象承载配置数据
|
9月前
|
数据库 C#
C#,.net,winform导入Excel功能以及下载Excel文件到本地,并使用SqlBulkCopy把DataTable类型的数据写入到sqlserver数据库中
C#,.net,winform导入Excel功能以及下载Excel文件到本地,并使用SqlBulkCopy把DataTable类型的数据写入到sqlserver数据库中
215 0
|
12月前
|
Web App开发
.Net Core下使用HtmlAgilityPack解析采集互联网数据
.Net Core下使用HtmlAgilityPack解析采集互联网数据
90 0
|
SQL 开发框架 .NET
在ASP.NET中使用ListView控件对数据进行显示、分页和排序
在ASP.NET中使用ListView控件对数据进行显示、分页和排序
在ASP.NET中使用ListView控件对数据进行显示、分页和排序