ASP.NET Web Forms 4.5的新特性(三):Model Binding

來源:互聯網
上載者:User

在前兩篇文章中,我們瞭解到了ASP.NET Web Forms 4.5四個新特性:強型別資料控制項和Bundling、針對HTML5的更新和Unobtrusive Validation。

在介紹強型別控制項的時候只是簡單介紹了下它具有ItemType的屬性,可以設定強型別值進行綁定,如果只是引入了這個屬性,那麼有點像文法糖,沒什麼實際意義。

其實許多園友也發現了在ASP.NET Web Forms 4.5中引入了許多MVC的特性,而Model Binding則是更加像MVC的一個特性了。

Model Binding

如果用過ObjectDataSource控制項,肯定對其SelectMethod有印象,在ASP.NET Web Forms 4.5中,微軟直接將此方法移到了強型別控制項上。

將之前DataBind方法直接替換成了更方便的SelectMethod方法,具體參見這裡。

SelectMethod方法接受IEnumerable或者IQueryable類型的對象,如果使用了前面介紹的ItemType屬性後,就需要接受IEnumerable<T>或者IQueryable<T>類型的對象,T與前面的ItemType一致。

如我們這樣設定一個GridView的配置。

 

 1 <form id="form1" runat="server">
 2     <div>
 3         <asp:GridView ID="GridView_Users" runat="server" ItemType="ModelBinding.Users"
 4             DataKeyNames="UserID" SelectMethod="GetUsers"
 5             AutoGenerateColumns="False">
 6             <Columns>
 7                 <asp:BoundField DataField="UserID" HeaderText="User ID" />
 8                 <asp:BoundField DataField="UserName" HeaderText="User Name" />
 9                 <asp:BoundField DataField="UserEmail" HeaderText="Email" />
10             </Columns>
11         </asp:GridView>
12         <asp:ValidationSummary ID="ValidationSummary_UserEdit" runat="server" ShowModelStateErrors="true" />
13     </div>
14 </form>

後台綁定資料。

1 public IQueryable<Users> GetUsers()
2 {
3     List<Users> list = new List<Users>();
4     list.Add(new Users() { UserID = 1, UserName = "Parry", UserEmail = "Parry@cnblogs.com" });
5     list.Add(new Users() { UserID = 2, UserName = "Spiderman", UserEmail = "Spiderman@cnblogs.com" });
6     list.Add(new Users() { UserID = 3, UserName = "Superman", UserEmail = "PaSupermanrry@cnblogs.com" });
7     list.Add(new Users() { UserID = 4, UserName = "Batman", UserEmail = "Batman@cnblogs.com" });
8     return list.AsQueryable<Users>();
9 }

頁面顯示。

當然,控制項還支援UpdateMethod和DeleteMethod分別進行修改和刪除操作。

需要注意的是,在後台定義的SelectMethod中也是可以定義參數屬性的。

public IQueryable<Users> GetUsers([Control]int? userID)

還支援Form、QueryString、Cookies、Url這些屬性。

整體感覺這部分是ASP.NET Web Forms 4.5變化較大,也是更像MVC的地方。微軟將EF,強型別控制項,Model Binding串聯起來,定義了一個規整的後台綁定的方法和流程。

更詳細的介紹可以參考ScottGu的系列文章:Web Forms Model Binding。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.