zoukankan      html  css  js  c++  java
  • 再接再厉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">
        
        
    public 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>

            public StartsWithAttribute(string param)
            
    {
                _param 
    = param;
            }


            
    /// <summary>
            
    /// 是否通过验证
            
    /// </summary>
            
    /// <param name="value">输入值</param>
            
    /// <returns></returns>

            public override bool IsValid(object value)
            
    {
                
    return ((string)value).ToLower().StartsWith(this._param.ToLower());
            }


            
    /// <summary>
            
    /// 格式化错误信息
            
    /// </summary>
            
    /// <param name="name">指定的字段名</param>
            
    /// <returns></returns>

            public 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>


    OK
    [源码下载]
  • 相关阅读:
    后缀数组 (Suffix Array) 学习笔记
    Miller-Rabin 素性测试 与 Pollard Rho 大整数分解
    [ USACO 2013 OPEN ] Photo
    清华集训2016做题记录
    「UNR#2」黎明前的巧克力
    「UNR#1」奇怪的线段树
    Atcoder Grand Contest 018 E
    「NOI2015」小园丁与老司机
    「集训队作业2018」三角形
    Codeforces 878 E. Numbers on the blackboard
  • 原文地址:https://www.cnblogs.com/webabcd/p/1396212.html
Copyright © 2011-2022 走看看