天天看點

再接再厲VS 2008 sp1 + .NET 3.5 sp1(8) - Dynamic Data(動态資料)

<a href="http://webabcd.blog.51cto.com/1787395/341154" target="_blank">[索引頁]</a>

<a href="http://down.51cto.com/data/99915#">[源碼下載下傳]</a>

再接再厲VS 2008 sp1 + .NET 3.5 sp1(8) - Dynamic Data(動态資料)

介紹

以Northwind為示例資料庫,示範Dynamic Data(動态資料)

MetaModel - 資料庫和域對象之間的映射的抽象

MetaModel.RegisterContext() - 使用指定的配置上下文注冊指定的資料上下文

Scaffold - 譯為基架。即基于資料庫架構(linq to sql 或 entity framework)生成網頁模闆的機制

ScaffoldTableAttribute(false) - 隐藏指定的表

ScaffoldColumn(false) - 隐藏指定的字段

MetadataTypeAttribute(Type metadataClassType) - 指定要與資料模型類關聯的中繼資料類

DynamicField - 顯示指定的動态資料字段,相當于 BoundField

DynamicControl - 通過指定的字段模闆顯示指定的動态資料字段

示例

全局配置

Global.asax

&lt;%@ Application Language="C#" %&gt; 

&lt;%@ Import Namespace="System.Web.Routing" %&gt; 

&lt;%@ Import Namespace="System.Web.DynamicData" %&gt; 

&lt;script runat="server"&gt; 

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 

                // }); 

                //         Action = PageAction.Details, 

        } 

        void Application_Start(object sender, EventArgs e) 

                RegisterRoutes(RouteTable.Routes); 

&lt;/script&gt;

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

        [MetadataType(typeof(Products_Metadata))] 

        public partial class Products 

                // entity framework 會自動生成類似 OnFieldChanging() 的部分方法 

                // 如果想做字段的自定義輸入驗證,則可以重寫此方法 

                partial void OnUnitPriceChanging(global::System.Nullable&lt;decimal&gt; value) 

                        if (value &gt; 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 { get; set; } 

        // 編寫一個自定義 ValidationAttribute,驗證指定字段是否是以指定的字元串開頭 

        [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] 

        sealed public class StartsWithAttribute : ValidationAttribute 

                readonly string _param; 

                /**//// &lt;summary&gt; 

                /// 構造函數 

                /// &lt;/summary&gt; 

                /// &lt;param name="param"&gt;指定的開頭字元串&lt;/param&gt; 

StartsWithAttribute() StartsWithAttribute(string param) 

                        _param = param; 

                /// 是否通過驗證 

                /// &lt;param name="value"&gt;輸入值&lt;/param&gt; 

                /// &lt;returns&gt;&lt;/returns&gt; 

override bool IsValid() override bool IsValid(object value) 

                        return ((string)value).ToLower().StartsWith(this._param.ToLower()); 

                /// 格式化錯誤資訊 

                /// &lt;param name="name"&gt;指定的字段名&lt;/param&gt; 

override string FormatErrorMessage() override string FormatErrorMessage(string name) 

                        return string.Format(ErrorMessageString, name, this._param); 

2、以 Products 表為例,示範動态資料的應用

MyProducts.aspx

&lt;%@ Page Language="C#" MasterPageFile="~/Site.master" CodeFile="MyProducts.aspx.cs" 

        Inherits="MyProducts" Title="以 Products 表為例,示範動态資料的應用" %&gt; 

&lt;%@ Register Assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 

        Namespace="System.Web.UI.WebControls" TagPrefix="asp" %&gt; 

&lt;asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"&gt; 

        &lt;asp:DynamicDataManager ID="DynamicDataManager1" runat="server" AutoLoadForeignKeys="true" /&gt; 

        &lt;h2&gt; 

                以 Products 表為例,示範動态資料的應用&lt;/h2&gt; 

        &lt;asp:FormView ID="FormView1" runat="server" DataSourceID="FormDataSource" AllowPaging="True" 

                DataKeyNames="ProductId"&gt; 

                &lt;ItemTemplate&gt; 

                        &lt;table&gt; 

                                &lt;tr&gt; 

                                        &lt;td&gt; 

                                                ProductId: 

                                        &lt;/td&gt; 

                                                &lt;!--DynamicField - 顯示指定的動态資料字段,相當于 BoundField--&gt; 

                                                &lt;!--DynamicControl - 通過指定的字段模闆顯示指定的動态資料字段--&gt; 

                                                &lt;asp:DynamicControl ID="ProductId" runat="server" DataField="ProductId" /&gt; 

                                &lt;/tr&gt; 

                                                ProductName: 

                                                &lt;asp:DynamicControl ID="ProductName" runat="server" DataField="ProductName" /&gt; 

                                                UnitPrice: 

                                                &lt;asp:DynamicControl ID="UnitPrice" runat="server" DataField="UnitPrice" /&gt; 

                                        &lt;td colspan="2"&gt; 

                                                &lt;asp:LinkButton ID="InsertButton" runat="server" CommandName="New" CausesValidation="false" 

                                                        Text="New" /&gt; 

                                                &lt;asp:LinkButton ID="EditButton" runat="server" CommandName="Edit" CausesValidation="false" 

                                                        Text="Edit" /&gt; 

                                                &lt;asp:LinkButton ID="DeleteButton" runat="server" CommandName="Delete" CausesValidation="false" 

                                                        Text="Delete" /&gt; 

                        &lt;/table&gt; 

                &lt;/ItemTemplate&gt; 

                &lt;EditItemTemplate&gt; 

                                                &lt;asp:DynamicControl ID="ProductId" runat="server" DataField="ProductId" Mode="ReadOnly" /&gt; 

                                                &lt;!-- 

                                                        UIHint - 指定字段模闆,此例的字段模闆會以黃色背景顯示資料 

                                                        Mode - 設定呈現模式 [System.Web.UI.WebControls.DataBoundControlMode 枚舉]    

                                                                DataBoundControlMode.ReadOnly - 隻讀模式。預設值 

                                                                DataBoundControlMode.Edit - 編輯模式 

                                                                DataBoundControlMode.Insert - 插入模式 

                                                --&gt; 

                                                &lt;asp:DynamicControl ID="ProductName" runat="server" DataField="ProductName" Mode="Edit" 

                                                        UIHint="YelloText" /&gt; 

                                                &lt;asp:DynamicControl ID="UnitPrice" runat="server" DataField="UnitPrice" Mode="Edit" /&gt; 

                                                &lt;asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update"&gt;Update&lt;/asp:LinkButton&gt; 

                                                &lt;asp:LinkButton ID="CancelEditButton" runat="server" CommandName="Cancel" CausesValidation="false"&gt;Cancel&lt;/asp:LinkButton&gt; 

                &lt;/EditItemTemplate&gt; 

                &lt;InsertItemTemplate&gt; 

                                                &lt;asp:DynamicControl ID="ProductName" runat="server" DataField="ProductName" Mode="Insert" /&gt; 

                                                &lt;asp:LinkButton ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" /&gt; 

                                                &lt;asp:LinkButton ID="CancelInsertButton" runat="server" CommandName="Cancel" CausesValidation="false" 

                                                        Text="Cancel" /&gt; 

                &lt;/InsertItemTemplate&gt; 

                &lt;PagerSettings Position="Bottom" Mode="NumericFirstLast" /&gt; 

        &lt;/asp:FormView&gt; 

        &lt;asp:EntityDataSource ID="FormDataSource" runat="server" ConnectionString="name=NorthwindEntities" 

                DefaultContainerName="NorthwindEntities" EntitySetName="Products" ContextTypeName="VS2008SP1.Business.NorthwindEntities" 

                EnableInsert="True" EnableUpdate="True" EnableDelete="True"&gt; 

        &lt;/asp:EntityDataSource&gt; 

&lt;/asp:Content&gt;

OK

     本文轉自webabcd 51CTO部落格,原文連結:http://blog.51cto.com/webabcd/341156,如需轉載請自行聯系原作者