.Net Framework 4.5與Visual Studio 11- ASP.NET 4.5新功能(2)

by vivid 14. 十二月 2011 01:00

.NET Magazine國際中文電子雜誌
作 者:許薰尹
審 稿:張智凱
文章編號:N111211901
出刊日期:2011/12/14

ASP.NET 4.5提供了模型繫結(Model Binding)功能,有點類似ASP.NET MVC的架構,利用code-focused的概念,讓程式設計師更精確地掌控網頁中伺服器控制項的資料繫結設計之細節,本文介紹如何透過模型繫結功能來查詢、顯示資料庫的資料,並進行資料分頁、排序、篩選的設計方式。本文撰寫時使用的工具是Visual Studio 11 Developer Preview,資料庫則為SQL Server “Denali” Express版,因此本文探討的內容在正式版上市時可能不適用。

在模型繫結(Model Binding)架構下,你可以在網頁中自行撰寫程式碼,設計方法(Method),來存取資料,然後將方法回傳的結果當作是伺服器控制項的資料來源,伺服器控制項會在適當時機呼叫這個方法以取得資料。除了透過方法取得資料之外,模型繫結架構也允許套用在新增資料、資料異動或刪除的情境,讓你更便於透過它在Web Form中操作資料。

使用SelectMethod設計模型繫結(Model Binding)

只要自行設計的方法能夠回傳實作IQueryable<T>、IEnumerable<T>的物件,便可以使用模型繫結這個功能。例如以下例子,網頁中包含一個GetContacts方法,此方法利用ADO.NET實體資料模型(ADO.NET Entity Data Model)取回AdventureWorks資料庫中Contact資料表中的內容,GetContacts方法,利用AsQueryable方法,回傳了實作IQueryable<AdventureWorksModel.Contact>介面的物件:

public IQueryable <AdventureWorksModel.Contact> GetContacts ()
  {
      var ctx = new AdventureWorksModel.AdventureWorksEntities ();
      return ctx.Contacts.AsQueryable<AdventureWorksModel.Contact> ();
  }

目前網頁中包含一個GridView控制項,其SelectMethod屬性設定為GetContacts,表示資料來自於GetContacts方法執行完所得到的結果,GridView控制項中利用BoundField來顯示欄位的內容:

<asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False"
       SelectMethod = "GetContacts" >
        <Columns>
            <asp:BoundField DataField = "ContactID" HeaderText = "ContactID" ReadOnly = "True"
                SortExpression = "ContactID" />
            <asp:CheckBoxField DataField = "NameStyle" HeaderText = "NameStyle"
                SortExpression = "NameStyle" />
            <asp:BoundField DataField = "Title" HeaderText = "Title" SortExpression = "Title" />
            <asp:BoundField DataField = "FirstName" HeaderText = "FirstName"
                SortExpression = "FirstName" />
            <asp:BoundField DataField = "MiddleName" HeaderText = "MiddleName"
                SortExpression = "MiddleName" />
            <asp:BoundField DataField = "LastName" HeaderText = "LastName"
                SortExpression = "LastName" />
            <asp:BoundField DataField = "Suffix" HeaderText = "Suffix"
                SortExpression = "Suffix" />
            <asp:BoundField DataField = "EmailAddress" HeaderText = "EmailAddress"
                SortExpression = "EmailAddress" />
            <asp:BoundField DataField = "EmailPromotion" HeaderText = "EmailPromotion"
                SortExpression = "EmailPromotion" />
            <asp:BoundField DataField = "Phone" HeaderText = "Phone" SortExpression = "Phone" />
            <asp:BoundField DataField = "PasswordHash" HeaderText = "PasswordHash"
                SortExpression = "PasswordHash" />
            <asp:BoundField DataField = "PasswordSalt" HeaderText = "PasswordSalt"
                SortExpression = "PasswordSalt" />
            <asp:BoundField DataField = "AdditionalContactInfo"
                HeaderText = "AdditionalContactInfo" SortExpression = "AdditionalContactInfo" />
            <asp:BoundField DataField = "rowguid" HeaderText = "rowguid"
                SortExpression = "rowguid" />
            <asp:BoundField DataField = "ModifiedDate" HeaderText = "ModifiedDate"
                SortExpression = "ModifiedDate" />
        </Columns>
    </asp:GridView>

這個範例的執行結果如下圖所示:

clip_image002

圖 1:使用模型繫結功能的網頁。

設計回傳IEnumerable<T>的SelectMethod方法

你也可以改寫GetContacts方法,使其回傳IEnumerable<T>,這樣也可以套用模型繫結的架構。例如,可以將上個範例中GetContacts方法改寫如下,使其回傳ObjectSet<T>,ObjectSet<T>實作了IEnumerable<T>:

public IEnumerable <AdventureWorksModel.Contact> GetContacts()
{
    var ctx = new AdventureWorksModel.AdventureWorksEntities ();
    return ctx.Contacts;
}

另一種作法便是利用AsEnumerable方法來轉換型別,例如底下的範例程式碼所示:

public IEnumerable <AdventureWorksModel.Contact> GetContacts()
{
    var ctx = new AdventureWorksModel.AdventureWorksEntities ();
    return ctx.Contacts.AsEnumerable<AdventureWorksModel.Contact> ();
}

只要方法回傳的結果是一個IEnumerable<T>型別的物件,都可以應用在模型繫結這個情境中,換言之,你不一定要使用ADO.NET實體資料模型(ADO.NET Entity Framework)來取回資料,可以改用自訂的集合來存放資料,例如有一個自訂的Employee類別如下,包含兩個屬性:ID與Name。

 

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

以下的範例網頁中包含一個GetEmployees方法,方法中建立兩個Employee物件,加入List<Employee>集合,方法將回傳List<Employee>,而網頁中的GridView控制項的SelectMethod設定為GetEmployees方法:

<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
    public IEnumerable <Employee> GetEmployees()
    {
         List<Employee> emps=null;
         emps = new List<Employee> () {
           new Employee() { ID = 1, Name = "Mary" },
           new Employee() { ID = 2, Name = "Candy"}
       };
        return emps;
    }
</script>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
</head>
<body>
    <form id = "form1" runat = "server">   
    <asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "false"
       ModelType = "Employee"
       SelectMethod = "GetEmployees" >
        <Columns>
            <asp:BoundField DataField = "ID" HeaderText = "ID" ReadOnly = "True"
                SortExpression = "ID" />       
            <asp:BoundField DataField = "Name" HeaderText = "Name"
                SortExpression = "Name" /> 
        </Columns>
    </asp:GridView> 
    </form>
</body>
</html>
在SelectMethod方法回傳相關聯資料

你也可以讓SelectMethod方法回傳有相關聯的資料表資料。例如以下範例利用LINQ語法,透過Include方法查詢出Contact以及相關聯的Employee 資料表資料,利用Where方法篩選出ContactID為1209的顧客資料,以及其相關聯的Employee資料。

<%@ Page Language = "C#" %>
<!DOCTYPE html>
<script runat = "server">
    public IQueryable <AdventureWorksModel.Contact> GetContacts ()
    {
        var ctx = new AdventureWorksModel.AdventureWorksEntities ();
        return ctx.Contacts.Include("Employees").Where( c => c.ContactID == 1209 ).AsQueryable<AdventureWorksModel.Contact> (); ;
    }
</script>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
</head>
<body>
    <form id = "form1" runat = "server">
      <asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False"
       ModelType = "AdventureWorksModel.Contact"
       SelectMethod = "GetContacts" >
        <Columns>
            <asp:BoundField DataField = "ContactID" HeaderText = "ContactID" ReadOnly = "True"
                SortExpression = "ContactID" />
            <asp:TemplateField HeaderText = "Employee Count" >
             <ItemTemplate> <%# Item.Employees.Count %> </ItemTemplate>
            </asp:TemplateField>    
        </Columns>
    </asp:GridView>
     </form>
</body>
</html>

在GridView控制項的TemplateField中,我們可以利用Count屬性,計算出某Contact相關聯的Employee資料筆數,參考執行結果:

clip_image004

圖 2:在SelectMethod方法回傳相關聯資料執行結果。

資料排序

若要讓資料隨使用者的喜好來進行排序,只要在資料繫結控制項啟用排序的功能即可,以GridView控制項來說,只要設定AllowSorting屬性為「True」,然後在GridView控制項中的每一個BoundColumn設定SortExpression來指明排序欄位就完成排序功能的設計。舉例來說,以下範例程式,利用Where方法篩選出ContactID小於1000的顧客資料顯示在GridView控制項上:

<%@ Page Language = "C#" %>

<!DOCTYPE html>
<script runat = "server">
    public IQueryable< AdventureWorksModel.Contact> GetContacts ()
    {
        var ctx = new AdventureWorksModel.AdventureWorksEntities ();
        return ctx.Contacts.Where( c => c.ContactID < 1000 );
    }
 
</script>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
</head>
<body>
    <form id = "form1" runat = "server">
    <asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False" ModelType = "AdventureWorksModel.Contact"
        SelectMethod = "GetContacts" AllowSorting = "True" >
        <Columns>
            <asp:BoundField DataField = "ContactID" HeaderText = "ContactID" ReadOnly = "True" SortExpression = "ContactID" />
            <asp:CheckBoxField DataField = "NameStyle" HeaderText = "NameStyle" SortExpression = "NameStyle" />
            <asp:BoundField DataField = "Title" HeaderText = "Title" SortExpression = "Title" />
            <asp:BoundField DataField = "FirstName" HeaderText = "FirstName" SortExpression = "FirstName" />
            <asp:BoundField DataField = "MiddleName" HeaderText = "MiddleName" SortExpression = "MiddleName" />
            <asp:BoundField DataField = "LastName" HeaderText = "LastName" SortExpression = "LastName" />
            <asp:BoundField DataField = "Suffix" HeaderText = "Suffix" SortExpression = "Suffix" />
            <asp:BoundField DataField = "EmailAddress" HeaderText = "EmailAddress" SortExpression = "EmailAddress" />
            <asp:BoundField DataField = "EmailPromotion" HeaderText = "EmailPromotion" SortExpression = "EmailPromotion" />
            <asp:BoundField DataField = "Phone" HeaderText = "Phone" SortExpression = "Phone" />
            <asp:BoundField DataField = "PasswordHash" HeaderText = "PasswordHash" SortExpression = "PasswordHash" />
            <asp:BoundField DataField = "PasswordSalt" HeaderText="PasswordSalt" SortExpression = "PasswordSalt" />
            <asp:BoundField DataField = "AdditionalContactInfo" HeaderText = "AdditionalContactInfo"
                SortExpression = "AdditionalContactInfo" />
            <asp:BoundField DataField = "rowguid" HeaderText = "rowguid" SortExpression = "rowguid" />
            <asp:BoundField DataField = "ModifiedDate" HeaderText = "ModifiedDate" SortExpression = "ModifiedDate" />
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

這個網頁的執行的結果如下,您可以點選欄位上方的超連結來進行升冪或降冪排序:

clip_image006

圖 3:資料排序。

資料分頁

若不希望一次顯示資料庫中資料表所有資料,而是讓資料以分頁方式來顯示,也是要從資料繫結控制項著手,但若將上例的GridView控制項AllowPaging屬性值設定為「True」,將分頁的功能啟用,你可能會得到一個錯誤訊息:「只對 LINQ to Entities 中的已排序輸入支援 'Skip' 方法。必須先呼叫 'OrderBy' 方法,然後再呼叫 'Skip' 方法。」,參考下圖所示:

clip_image008

圖 4:資料分頁錯誤訊息。

錯誤訊息中已經描述的很詳細,取回資料時應該先叫用OrderBy方法進行初步排序,因此這個範例只需要將GetContacts方法修改如下,先叫用OrderBy方法,根據你屬意的欄位,如ContactID,來進行排序:

public IQueryable <AdventureWorksModel.Contact> GetContacts ()
  {
      var ctx = new AdventureWorksModel.AdventureWorksEntities ();
      return ctx.Contacts.Where( c => c.ContactID < 1000 ).OrderBy( c => c.ContactID );
  }

使用查詢字串做資料篩選

網頁程式講求效能要快,只要將必要的資料顯示出來,因此資料篩選動作是不可或缺的。您當然可以在模型繫結架構中可以加入資料篩選的功能,資料篩選的條件可以來自於Control、Cookie、Form、QueryString、ViewState…等等。

設計用來做為SelectMethod的方法時,若在方法參數的前方加上System.Web.ModelBinding.QueryString Attribute,則網頁執行時,模型繫結系統便會將查詢字串繫結到你指定的參數,並自動進行型別轉換的動作,參考以下範例,GetContacts方法傳入一個cID參數,以本例來說便是將查詢字串的值 ,轉換成int型別,然後透過LINQ的Where方法來篩選:

public IQueryable <AdventureWorksModel.Contact> GetContacts ( [System.Web.ModelBinding.QueryString] int cID )
{
     var ctx = new AdventureWorksModel.AdventureWorksEntities ();
     return ctx.Contacts.Where( c => c.ContactID < cID ).OrderBy( c => c.ContactID );
}

預設參數的名稱便是查詢字串的key值,因此你可以使用以下查詢字串指定cID的值為1000:

http://localhost:2498/yourpage.aspx?cID=1000

若要為查詢字串取一個更易識別名稱當作key值,只要傳入一個字串到QueryString Attribute的建構函式即可,例如底下將查詢字串的key值命為「id」:

public IQueryable <AdventureWorksModel.Contact> GetContacts ( [System.Web.ModelBinding.QueryString ("id")] int cID )
{
     var ctx = new AdventureWorksModel.AdventureWorksEntities ();
     return ctx.Contacts.Where( c => c.ContactID < cID ).OrderBy( c => c.ContactID );
}

這樣我們就使用以下查詢字串來進行查詢篩選ContactID為1000的資料出來:

http://localhost:2498/yourpage.aspx?id=1000

若執行時未設定查詢字串,例如使用以下URI:

http://localhost:2498/yourpage.aspx

則執行時會得到以下錯誤訊息,參考圖5所示:

「A null value for parameter 'cID' of non-nullable type 'System.Int32' for method 'System.Linq.IQueryable`1[AdventureWorksModel.Contact] GetContacts(Int32)' in 'ASP._10_modelbindingselectfilter_aspx'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.」

clip_image010

圖 5:未設定查詢字串的錯誤訊息。

此時可以修改程式碼將查詢字串對應的cID變數,宣告成nullable型別來解決這個問題:

public IQueryable <AdventureWorksModel.Contact> GetContacts( [System.Web.ModelBinding.QueryString("id") ] int? cID )
    {
        var ctx = new AdventureWorksModel.AdventureWorksEntities ();
        return ctx.Contacts.Where( c => c.ContactID < cID ).OrderBy( c => c.ContactID );
    }
使用控制項進行資料篩選

若篩選的條件是決定於特定控制項的值,您可以在SelectMethod方法的參數上套用Control Attribute,例如以下範例中,DropDownList控制項的ID為「cID」,模型繫結系統會自動將DropDownList控制項選取的值繫結到SelectMethod方法的cID參數上:

<%@ Page Language = "C#" %>

<!DOCTYPE html>
<script runat = "server">
    public IQueryable< AdventureWorksModel.Contact > GetContacts( [System.Web.ModelBinding.Control] int? cID )
    {
        var ctx = new AdventureWorksModel.AdventureWorksEntities ();
        return ctx.Contacts.Where( c => c.ContactID < cID ).OrderBy( c => c.ContactID );
    }
</script>
<html xmlns = http://www.w3.org/1999/xhtml >
<head runat = "server">
    <title> </title>
</head>
<body>
    <form id = "form1" runat = "server">
    <asp:DropDownList runat = "server" ID = "cID" AutoPostBack = "True" >
        <asp:ListItem> 1000 </asp:ListItem>
        <asp:ListItem> 2000 </asp:ListItem>
        <asp:ListItem> 3000 </asp:ListItem>
        <asp:ListItem> 4000 </asp:ListItem>
        <asp:ListItem> 5000 </asp:ListItem>
        <asp:ListItem> 6000 </asp:ListItem>
        <asp:ListItem> 7000 </asp:ListItem>
        <asp:ListItem> 8000 </asp:ListItem>
        <asp:ListItem> 9000 </asp:ListItem>
    </asp:DropDownList>
    <br />
    <asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False" ModelType = "AdventureWorksModel.Contact"
        SelectMethod = "GetContacts" AllowSorting = "True" AllowPaging = "True" >
        <Columns>
            <asp:BoundField DataField = "ContactID" HeaderText = "ContactID" ReadOnly = "True" SortExpression = "ContactID" />
            <asp:CheckBoxField DataField = "NameStyle" HeaderText = "NameStyle" SortExpression = "NameStyle" />
            <asp:BoundField DataField = "Title" HeaderText = "Title" SortExpression = "Title" />
            <asp:BoundField DataField = "FirstName" HeaderText = "FirstName" SortExpression = "FirstName" />
            <asp:BoundField DataField = "MiddleName" HeaderText = "MiddleName" SortExpression = "MiddleName" />
            <asp:BoundField DataField = "LastName" HeaderText = "LastName" SortExpression = "LastName" />
            <asp:BoundField DataField = "Suffix" HeaderText = "Suffix" SortExpression = "Suffix" />
            <asp:BoundField DataField = "EmailAddress" HeaderText = "EmailAddress" SortExpression = "EmailAddress" />
            <asp:BoundField DataField = "EmailPromotion" HeaderText = "EmailPromotion" SortExpression = "EmailPromotion" />
            <asp:BoundField DataField = "Phone" HeaderText = "Phone" SortExpression = "Phone" />
            <asp:BoundField DataField = "PasswordHash" HeaderText = "PasswordHash" SortExpression = "PasswordHash" />
            <asp:BoundField DataField = "PasswordSalt" HeaderText = "PasswordSalt" SortExpression = "PasswordSalt" />
            <asp:BoundField DataField = "AdditionalContactInfo" HeaderText = "AdditionalContactInfo"
                SortExpression = "AdditionalContactInfo" />
            <asp:BoundField DataField = "rowguid" HeaderText = "rowguid" SortExpression = "rowguid" />
            <asp:BoundField DataField = "ModifiedDate" HeaderText = "ModifiedDate" SortExpression = "ModifiedDate" />
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

若要為控制項取一個有意義的名稱,如本例中將DropdownList控制項的ID設定為「ddl」,則只需要在設定Control Attribute 時,傳入字串到Control Attribute的建構函式來指明它的ID名稱即可:

<%@ Page Language = "C#" %>

<!DOCTYPE html>
<script runat = "server">
    public IQueryable <AdventureWorksModel.Contact> GetContacts ( [System.Web.ModelBinding.Control("ddl")] int? cID)
    {
        var ctx = new AdventureWorksModel.AdventureWorksEntities ();
        return ctx.Contacts.Where( c => c.ContactID < cID ).OrderBy( c => c.ContactID );
    }
</script>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
</head>
<body>
    <form id = "form1" runat = "server">
    <asp:DropDownList runat = "server" ID = "ddl" AutoPostBack="True">
        <asp:ListItem> 1000 </asp:ListItem>
        <asp:ListItem> 2000 </asp:ListItem>
        <asp:ListItem> 3000 </asp:ListItem>
        <asp:ListItem> 4000 </asp:ListItem>
        <asp:ListItem> 5000 </asp:ListItem>
        <asp:ListItem> 6000 </asp:ListItem>
        <asp:ListItem> 7000 </asp:ListItem>
        <asp:ListItem> 8000 </asp:ListItem>
        <asp:ListItem> 9000 </asp:ListItem>
    </asp:DropDownList>
    <br />
    <asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False" ModelType = "AdventureWorksModel.Contact"
        SelectMethod = "GetContacts" AllowSorting = "True" AllowPaging = "True" >
        <Columns>
            <asp:BoundField DataField = "ContactID" HeaderText = "ContactID" ReadOnly = "True" SortExpression = "ContactID" />
            <asp:CheckBoxField DataField = "NameStyle" HeaderText = "NameStyle" SortExpression = "NameStyle" />
            <asp:BoundField DataField = "Title" HeaderText = "Title" SortExpression = "Title" />
            <asp:BoundField DataField = "FirstName" HeaderText = "FirstName" SortExpression = "FirstName" />
            <asp:BoundField DataField = "MiddleName" HeaderText = "MiddleName" SortExpression = "MiddleName" />
            <asp:BoundField DataField = "LastName" HeaderText = "LastName" SortExpression = "LastName" />
            <asp:BoundField DataField = "Suffix" HeaderText = "Suffix" SortExpression = "Suffix" />
            <asp:BoundField DataField = "EmailAddress" HeaderText = "EmailAddress" SortExpression = "EmailAddress" />
            <asp:BoundField DataField = "EmailPromotion" HeaderText = "EmailPromotion" SortExpression = "EmailPromotion" />
            <asp:BoundField DataField = "Phone" HeaderText = "Phone" SortExpression = "Phone" />
            <asp:BoundField DataField = "PasswordHash" HeaderText = "PasswordHash" SortExpression = "PasswordHash" />
            <asp:BoundField DataField = "PasswordSalt" HeaderText = "PasswordSalt" SortExpression = "PasswordSalt" />
            <asp:BoundField DataField = "AdditionalContactInfo" HeaderText = "AdditionalContactInfo"
                SortExpression = "AdditionalContactInfo" />
            <asp:BoundField DataField = "rowguid" HeaderText = "rowguid" SortExpression = "rowguid" />
            <asp:BoundField DataField = "ModifiedDate" HeaderText = "ModifiedDate" SortExpression = "ModifiedDate" />
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

使用Form進行資料篩選

由於資料篩選的條件可以來自於Control、Cookie、Form、QueryString、ViewState…等等,若要使用Form來進行篩選可以參考以下範例程式碼,其中包含一個ID為TextBox1的文字方塊,我們希望將文字方塊輸入的內容當作是資料篩選的條件。因此,只要在GetContacts方法的傳入參數宣告的前方,加上Form Attribute,在建構函式中指明TextBox1即可。

這個範例執行的結果請參考下圖所示。

clip_image012

圖 6:使用Form設定篩選條件。

 

<%@ Page Language = "C#" %>
<!DOCTYPE html>
<script runat="server">
    public IQueryable< AdventureWorksModel.Contact> GetContacts( [System.Web.ModelBinding.Form("TextBox1") ] int? cID)
    {
        var ctx = new AdventureWorksModel.AdventureWorksEntities ();
        return ctx.Contacts.Where( c => c.ContactID < cID ).OrderBy( c => c.ContactID );
    }
</script>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
</head>
<body>
    <form id = "form1" runat = "server">
    <asp:TextBox ID = "TextBox1" runat = "server" Text = "1000"> </asp:TextBox>
    <asp:Button ID = "Button1" runat = "server" Text = "Query" />
    <br />
    <asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False" ModelType = "AdventureWorksModel.Contact"
        SelectMethod = "GetContacts" AllowSorting = "True" AllowPaging = "True" >
        <Columns>
            <asp:BoundField DataField = "ContactID" HeaderText = "ContactID" ReadOnly = "True" SortExpression = "ContactID" />
            <asp:CheckBoxField DataField = "NameStyle" HeaderText = "NameStyle" SortExpression = "NameStyle" />
            <asp:BoundField DataField = "Title" HeaderText = "Title" SortExpression = "Title" />
            <asp:BoundField DataField = "FirstName" HeaderText = "FirstName" SortExpression = "FirstName" />
            <asp:BoundField DataField = "MiddleName" HeaderText = "MiddleName" SortExpression = "MiddleName" />
            <asp:BoundField DataField = "LastName" HeaderText = "LastName" SortExpression = "LastName" />
            <asp:BoundField DataField = "Suffix" HeaderText = "Suffix" SortExpression = "Suffix" />
            <asp:BoundField DataField = "EmailAddress" HeaderText = "EmailAddress" SortExpression = "EmailAddress" />
            <asp:BoundField DataField = "EmailPromotion" HeaderText = "EmailPromotion" SortExpression = "EmailPromotion" />
            <asp:BoundField DataField = "Phone" HeaderText = "Phone" SortExpression = "Phone" />
            <asp:BoundField DataField = "PasswordHash" HeaderText = "PasswordHash" SortExpression = "PasswordHash" />
            <asp:BoundField DataField = "PasswordSalt" HeaderText = "PasswordSalt" SortExpression = "PasswordSalt" />
            <asp:BoundField DataField = "AdditionalContactInfo" HeaderText = "AdditionalContactInfo"
                SortExpression = "AdditionalContactInfo" />
            <asp:BoundField DataField = "rowguid" HeaderText = "rowguid" SortExpression = "rowguid" />
            <asp:BoundField DataField = "ModifiedDate" HeaderText = "ModifiedDate" SortExpression = "ModifiedDate" />
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>
使用ViewState進行資料篩選

最後我們再看一個範例,以ViewState中的值作為資料篩選條件。以下的範例程式中包含一個Button控制項,當按下按鈕時,設定ViewState["cID"]的值為1000,而做為SelectMethod的GetContacts方法第一個參數前方套用了ViewState Attribute。

<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
    public IQueryable< AdventureWorksModel.Contact> GetContacts( [System.Web.ModelBinding.ViewState()] int? cID )
    {
        var ctx = new AdventureWorksModel.AdventureWorksEntities ();
        return ctx.Contacts.Where( c => c.ContactID < cID ).OrderBy( c => c.ContactID );
    }

    protected void Button1_Click( object sender, EventArgs e )
    {
        ViewState["cID"] = 1000;
    }
</script>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
</head>
<body>
    <form id = "form1" runat = "server">
   
    <asp:Button ID = "Button1" runat = "server" Text = "Query" OnClick = "Button1_Click" />
    <br />
    <asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False" ModelType = "AdventureWorksModel.Contact"
        SelectMethod = "GetContacts" AllowSorting = "True" AllowPaging = "True">
        <Columns>
            <asp:BoundField DataField = "ContactID" HeaderText = "ContactID" ReadOnly = "True" SortExpression = "ContactID" />
            <asp:CheckBoxField DataField = "NameStyle" HeaderText = "NameStyle" SortExpression = "NameStyle" />
            <asp:BoundField DataField = "Title" HeaderText = "Title" SortExpression = "Title" />
            <asp:BoundField DataField = "FirstName" HeaderText = "FirstName" SortExpression = "FirstName" />
            <asp:BoundField DataField = "MiddleName" HeaderText = "MiddleName" SortExpression = "MiddleName" />
            <asp:BoundField DataField = "LastName" HeaderText = "LastName" SortExpression = "LastName" />
            <asp:BoundField DataField = "Suffix" HeaderText = "Suffix" SortExpression = "Suffix" />
            <asp:BoundField DataField = "EmailAddress" HeaderText = "EmailAddress" SortExpression = "EmailAddress" />
            <asp:BoundField DataField = "EmailPromotion" HeaderText = "EmailPromotion" SortExpression = "EmailPromotion" />
            <asp:BoundField DataField = "Phone" HeaderText = "Phone" SortExpression = "Phone" />
            <asp:BoundField DataField = "PasswordHash" HeaderText = "PasswordHash" SortExpression = "PasswordHash" />
            <asp:BoundField DataField = "PasswordSalt" HeaderText = "PasswordSalt" SortExpression = "PasswordSalt" />
            <asp:BoundField DataField = "AdditionalContactInfo" HeaderText = "AdditionalContactInfo"
                SortExpression = "AdditionalContactInfo" />
            <asp:BoundField DataField = "rowguid" HeaderText = "rowguid" SortExpression = "rowguid" />
            <asp:BoundField DataField = "ModifiedDate" HeaderText = "ModifiedDate" SortExpression = "ModifiedDate" />
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

Tags:

NET 開發 | ASP.NET | .NET Magazine國際中文電子雜誌 | 許薰尹Vivid Hsu

新增評論




  Country flag
biuquote
  • 評論
  • 線上預覽
Loading






NET Magazine國際中文電子雜誌

NET Magazine國際中文電子版雜誌,由恆逸資訊創立於2000,自發刊日起迄今已發行超過500篇.NET相關技術文章,擁有超過40000名註冊讀者群。NET Magazine國際中文電子版雜誌希望藉於電子雜誌與NET Developer達到共同學習與技術新知分享,歡迎每一位對.NET 技術有興趣的朋友們多多支持本雜誌,讓作者群們可以有持續性的動力繼續爬文。<請加入免費訂閱>

月分類Month List