首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

VS 2008 SP1 + .NET 3.5 SP1 (8) - ASP.NET Dynamic Data 動態資料架構

     編輯:關於.NET

簡介

ASP.NET Dynamic Data 是一種基於資料庫結構(LINQ to SQL 或 Entity Framework)自動產生網頁模板的機制(Scaffolding),能快速建立資料驅動的 Web 應用程式。本文以 Northwind 資料庫為例,示範核心概念與實作。

核心概念

  • MetaModel:資料庫與領域物件之間映射的抽象層。
  • MetaModel.RegisterContext():註冊資料上下文與配置。
  • Scaffold (基架):依資料庫結構自動生成列表、詳細、編輯、新增頁面的機制。
  • ScaffoldTableAttribute(false):隱藏特定資料表。
  • ScaffoldColumn(false):隱藏特定欄位。
  • MetadataTypeAttribute:指定與資料模型類別關聯的中繼資料類別,用於加入驗證、顯示名稱等屬性。
  • DynamicField / DynamicControl:分別相當於 BoundField,以及透過欄位模板顯示動態資料欄位。

全域設定 - 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();
    model.RegisterContext(typeof(VS2008SP1.Business.NorthwindEntities), 
        new ContextConfiguration() { ScaffoldAllTables = true });

    // 分頁模式:列表、詳細、編輯、新增使用不同頁面
    routes.Add(new DynamicDataRoute("{table}/{action}.aspx") {
        Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
        Model = model
    });

    // 合併頁模式:所有操作在同一頁面(註解掉)
    // routes.Add(new DynamicDataRoute("{table}/ListDetails.aspx") { ... });
}
void Application_Start(object sender, EventArgs e) {
    RegisterRoutes(RouteTable.Routes);
}
</script>

中繼資料與驗證 - Scaffold.cs / Validation.cs

隱藏資料表與欄位

[ScaffoldTable(false)]
public partial class Region { }

[MetadataType(typeof(Customers_Metadata))]
public partial class Customers { }

public class Customers_Metadata {
    [ScaffoldColumn(false)]
    public object Phone; // 隱藏 Phone 欄位
}

自訂驗證屬性與欄位模板

[MetadataType(typeof(Products_Metadata))]
public partial class Products {
    partial void OnUnitPriceChanging(decimal? value) {
        if (value > 1000) throw new ValidationException("UnitPrice 不能大於 1000");
    }
}

public class Products_Metadata {
    [Required()]
    [UIHint("MyDecimal")] // 使用自訂欄位模板
    public object UnitPrice;

    [DisplayName("產品名稱")]
    [StartsWith("webabcd", ErrorMessage = "{0} 必須以 {1} 開頭")]
    public object ProductName { get; set; }
}

// 自訂驗證屬性
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class StartsWithAttribute : ValidationAttribute {
    readonly string _param;
    public StartsWithAttribute(string param) { _param = param; }
    public override bool IsValid(object value) {
        return ((string)value).ToLower().StartsWith(_param.ToLower());
    }
    public override string FormatErrorMessage(string name) {
        return string.Format(ErrorMessageString, name, _param);
    }
}

實際頁面應用 - MyProducts.aspx

使用 FormView 搭配 DynamicControl 實現 Products 資料表的 CRUD 操作,並示範 UIHint 指定編輯模式下的欄位模板:

<asp:DynamicDataManager ID="DynamicDataManager1" runat="server" AutoLoadForeignKeys="true" />
<asp:FormView ID="FormView1" runat="server" DataSourceID="FormDataSource" AllowPaging="True" DataKeyNames="ProductId">
    <ItemTemplate>
        <table>
            <tr><td>ProductId:</td><td><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 CommandName="New" Text="New" /> ... </td></tr>
        </table>
    </ItemTemplate>
    <EditItemTemplate>
        <table>
            <tr><td>ProductName:</td><td><asp:DynamicControl ID="ProductName" runat="server" DataField="ProductName" Mode="Edit" UIHint="YelloText" /></td></tr>
            ...
        </table>
    </EditItemTemplate>
    <InsertItemTemplate> ... </InsertItemTemplate>
</asp:FormView>
<asp:EntityDataSource ID="FormDataSource" runat="server" ConnectionString="name=NorthwindEntities" ... />

總結

Dynamic Data 透過慣例優於配置,結合中繼資料屬性,能快速建構功能完整的資料管理介面。完整原始碼請見:https://www.bianceng.net/dotnet/201212/807.htm

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved