UI Và Navigation

toi1em

Member
Feb 20, 2012
949
0
16
40
320x50.jpg


Mục lục bài viết


Trong bài hướng dẫn này, chúng ta sẽ sửa lại UI mặc định của ứng dụng Web. Ta sẽ thêm một vài đường dẫn để điều hướng. Bài này là phần tiếp theo của “Create the Data Access Layer” đã làm ở phần trước.

Chúng ta sẽ học:


– Thay đổi giao diện

– Điều hướng.

– Các hiển thị dữ liệu từ database đã tạo bằng EF CodeFirst.

ASP.NET Web Forms cho phép ta tạo các nội dung động cho ứng dụng. Mỗi page được tạo tương tự như tạo một trang HTML tĩnh. Trang ASP.NET sẽ nhận và xử lí việc sinh ra mã HTML mỗi khi trang chạy.

Chỉnh sửa UI


Ta sẽ tiếp tục bài hướng dẫn bằng việc sửa trang Default.aspx. Ta sẽ thay đổi tiêu đề, nội dung và bỏ các phần không cần thiết.

  1. Mở Mở Default.aspx page
  2. Nếu đang ở chế độ Design, ta chuyển sang Source
  3. Ở trên cùng, ta thêm dòng

<%@ Page Title="Welcome" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DMWingtipToys._Default" %>


1

<%@ Page Title="Welcome" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DMWingtipToys._Default" %>
  1. Thay thế nội dung mặc định trong <asp:Content> bởi nội dung ta muốn hiển thị, ví dụ:

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"> <h1><%: Title %>.</h1> <h2>welcome to My Shop</h2> <p class="lead"> Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. </p> </asp:Content>



1

2

3

4

5

6

7


<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

<h1><%: Title %>.</h1>

<h2>welcome to My Shop</h2>

<p class="lead">

Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.

</p>

</asp:Content>
  1. Lưu lại các thay đổi.

Kết quả sau khi thay đổi:


<%@ Page Title="Welcome" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DMWingtipToys._Default" %> <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"> <h1><%: Title %>.</h1> <h2>Welcome to My Shop</h2> <p class="lead"> Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. </p> </asp:Content>



1

2

3

4

5

6

7

8


<%@ Page Title="Welcome" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DMWingtipToys._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

<h1><%: Title %>.</h1>

<h2>Welcome to My Shop</h2>

<p class="lead">

Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.

</p>

</asp:Content>

Như ví dụ , ta đã đặt thuộc tính Title của chỉ thị @Page. Đoạn code: <%: Page.Title %> sẽ hiển thị tiêu đề cho các nội dung.

Trang ví dụ trên chứa các phần tử cơ bản nhất để tạo thành một trang ASP.NET hoàn chỉnh. Nội dung chứa trong Default.aspx sẽ tích hợp với trang master page, chúng ta sẽ tìm hiểu tí nữa.

Chỉ thị @Page


ASP.NET Web Forms thường chứa các chỉ thị cho chúng ta qui định các thuộc tính và thông tin cấu hình của trang, được ASP.NET dùng như một hướng dẫn để xử lí trang và không hiển thị ra trình duyệt.

Chỉ thị được dùng nhiều nhất là @Page, cho phép ta qui định một số lựa chọn trong việc cấu hình trang như sau:

– Ngôn ngữ phía Server cho các code trong trang, ví dụ: C#.

– Trang code-behind .

– Trang Master

– Lựa chọn Debugging hay Tracing

Nếu bạn không thêm vào chỉ thị @Page, các cài đặt sẽ kế thừa từ file Web.config hay từ Machine.config.

Web Server Controls


Trong hầu hết các ứng dụng ASP.NET Web Forms ta sẽ thêm vào các điều khiển cho phép người dùng tương tác với trang như button, textbox… . Web Server control tương tự như HTML control, tuy nhiên nó được xử lí phía Server, cho phép cài đặt các sự kiện sẽ xử lí phía Server.

Các thẻ trong Server control có tên bắt đầu với tiền tố asp: . Cho phép ASP.NET xử lí control đó. Tiền tố này có thể khác nếu nó không thuộc .NET Framework. Ngoài ra Server control còn chứa thuộc tính runat=”server” và một ID cho phép sử dụng trong phần Server code.

Server Code


Hầu hết ASP.NET Web Forms có chứa phần Code chạy trên Server khi Page được xử lí. Như đã đề cập ở phần trước, Server code có thể dùng để thực hiện nhiều việc, như thêm dữ liệu vào control ListView. ASP.NET hỗ trợ nhiều ngôn ngữ chạy phía Server, gồm: C#, VB, J# … .

ASP.NET hỗ trợ 2 mô hình viết Server code cho trang Web. Trong mô hình Single-file, các mã được bao trong phần tử script với thuộc tính runat = “server” . Ngoài ra bạn có thể viết Server code trong một trang riêng biệt gọi là mô hình Code-behind.

Thuộc tính CodeBehind chứa trong chỉ thị @Page định ra tên của class và thuộc tính Inherits chỉ ra trang Webform tương ứng.

Cập nhật Master Page


Master Page cho phép bạn tạo một layout phù hợp cho Page, nó như một chuẩn chung áp dụng cho tất cả các Page khác.

Trong ví dụ này, ta sẽ thêm vào một logo để hiển thị cho tất cả các Page bằng việc sửa mã HTML ở trang Master như sau:

  1. Mở trang Site.Master
  2. Nếu đang ở chế độ Design, cần chuyển sang Source
  3. Cập nhật lại trang Site.Master như sau:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="DMWingtipToys.SiteMaster" %> <!DOCTYPE html> <html lang="en"> <head runat="server"> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title><%: Page.Title %> My Shop</title> <asp:placeHolder runat="server"> <%: Scripts.Render("~/bundles/modernizr") %> </asp:placeHolder> <webopt:bundlereference runat="server" path="~/Content/css" /> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> </head> <body> <form runat="server"> <asp:ScriptManager runat="server"> <Scripts> <%--To learn more about bundling scripts in ScriptManager see http://go.microsoft.com/fwlink/?LinkID=301884 --%> <%--Framework Scripts--%> <asp:ScriptReference Name="MsAjaxBundle" /> <asp:ScriptReference Name="jquery" /> <asp:ScriptReference Name="bootstrap" /> <asp:ScriptReference Name="respond" /> <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" /> <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" /> <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" /> <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" /> <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" /> <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" /> <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" /> <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" /> <asp:ScriptReference Name="WebFormsBundle" /> <%--Site Scripts--%> </Scripts> </asp:ScriptManager> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" runat="server" href="~/">Wingtip Toys</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a runat="server" href="~/">Home</a></li> <li><a runat="server" href="~/About">About</a></li> <li><a runat="server" href="~/Contact">Contact</a></li> </ul> <asp:LoginView runat="server" ViewStateMode="Disabled"> <AnonymousTemplate> <ul class="nav navbar-nav navbar-right"> <li><a runat="server" href="~/Account/Register">Register</a></li> <li><a runat="server" href="~/Account/Login">Log in</a></li> </ul> </AnonymousTemplate> <LoggedInTemplate> <ul class="nav navbar-nav navbar-right"> <li><a runat="server" href="~/Account/Manage" title="Manage your account">Hello, <%: Context.User.Identity.GetUserName() %> !</a></li> <li> <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Log off" LogoutPageUrl="~/" OnLoggingOut="Unnamed_LoggingOut" /> </li> </ul> </LoggedInTemplate> </asp:LoginView> </div> </div> </div> <div id="TitleContent" style="text-align: center"> <a runat="server" href="~/"> <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/logo.jpg" BorderStyle="None" /> </a> <br /> </div> <div class="container body-content"> <asp:ContentPlaceHolder ID="MainContent" runat="server"> </asp:ContentPlaceHolder> <hr /> <footer> <p>&copy; <%: DateTime.Now.Year %> - tonii.xyz, co, ltd </p> </footer> </div> </form> </body> </html>



1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="DMWingtipToys.SiteMaster" %>

<!DOCTYPE html>

<html lang="en">

<head runat="server">

<meta charset="utf-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<title><%: Page.Title %> My Shop</title>

<asp:placeHolder runat="server">

<%: Scripts.Render("~/bundles/modernizr") %>

</asp:placeHolder>

<webopt:bundlereference runat="server" path="~/Content/css" />

<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

</head>

<body>

<form runat="server">

<asp:ScriptManager runat="server">

<Scripts>

<%--To learn more about bundling scripts in ScriptManager see http://go.microsoft.com/fwlink/?LinkID=301884 --%>

<%--Framework Scripts--%>

<asp:ScriptReference Name="MsAjaxBundle" />

<asp:ScriptReference Name="jquery" />

<asp:ScriptReference Name="bootstrap" />

<asp:ScriptReference Name="respond" />

<asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />

<asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />

<asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />

<asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />

<asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />

<asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />

<asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />

<asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />

<asp:ScriptReference Name="WebFormsBundle" />

<%--Site Scripts--%>

</Scripts>

</asp:ScriptManager>

<div class="navbar navbar-inverse navbar-fixed-top">

<div class="container">

<div class="navbar-header">

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

<span class="icon-bar"></span>

<span class="icon-bar"></span>

<span class="icon-bar"></span>

</button>

<a class="navbar-brand" runat="server" href="~/">Wingtip Toys</a>

</div>

<div class="navbar-collapse collapse">

<ul class="nav navbar-nav">

<li><a runat="server" href="~/">Home</a></li>

<li><a runat="server" href="~/About">About</a></li>

<li><a runat="server" href="~/Contact">Contact</a></li>

</ul>

<asp:LoginView runat="server" ViewStateMode="Disabled">

<AnonymousTemplate>

<ul class="nav navbar-nav navbar-right">

<li><a runat="server" href="~/Account/Register">Register</a></li>

<li><a runat="server" href="~/Account/Login">Log in</a></li>

</ul>

</AnonymousTemplate>

<LoggedInTemplate>

<ul class="nav navbar-nav navbar-right">

<li><a runat="server" href="~/Account/Manage" title="Manage your account">Hello, <%: Context.User.Identity.GetUserName() %> !</a></li>

<li>

<asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Log off" LogoutPageUrl="~/" OnLoggingOut="Unnamed_LoggingOut" />

</li>

</ul>

</LoggedInTemplate>

</asp:LoginView>

</div>

</div>

</div>

<div id="TitleContent" style="text-align: center">

<a runat="server" href="~/">

<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/logo.jpg" BorderStyle="None" />

</a>

<br />

</div>

<div class="container body-content">

<asp:ContentPlaceHolder ID="MainContent" runat="server">

</asp:ContentPlaceHolder>

<hr />

<footer>

<p>&copy; <%: DateTime.Now.Year %> - tonii.xyz, co, ltd </p>

</footer>

</div>

</form>

</body>

</html>

Đoạn code HTML trên sẽ hiển thị một hình ảnh với tên “logo.jpg” từ thư mục “Images” mà lát nữa ta sẽ thêm. Khi click vào logo, ta sẽ quay lại trang Default.aspx, do hình ảnh được đặt trong cặp thẻ <a>, giá trị “~/” trong “href” được hiểu rằng đó là trang gốc của Web site.

Master Page


Master page là một file ASP.NET với phần mở rộng .master(Vd: Site.Master) với layout được thiết kế sẵn, có thể bao gồm một số nội dung text, các phần tử HTML và cả Server control. Nó có chỉ thị @MASTER được khai báo ở đầu trang.

Trong Master page ta có control ContentPlaceHolder để giữ chỗ cho nội dung hiển thị. Trong các Page chứa nội dung(ví dụ: Default.aspx), ta dùng control Content để thêm nội dung hiển thị vào.

Thêm ảnh


Như đã đề cập ở trên, hình logo cùng với hình các product phải được thêm vào Web để người dùng có thể nhìn thấy trên trình duyệt.

Đây là toàn bộ nội dung của project, trong đó có chứa các hình ảnh mà ta sẽ sử dụng, bạn sẽ down tại đây.

  1. Tải project về, giải nén ra, tìm folder Catalog.
  2. Kéo và thả folder Catalog vào trong project.
  3. 1-0
  4. Tạo một folder mới tên Images để chứa logo.
  5. Copy file logo.jpg nằm trong folder Images từ project vừa down về và dán vào foler vừa tạo.
  6. Nếu không thấy hiển thị hình ảnh trong Project, ta cần click chọn Show All Files.
    1-1
Thêm các Page


Trước khi tạo các điều hướng cho trang, ta phải thêm vào 2 trang mới mà ta sẽ điều hướng đến. Danh sách các product và product details sẽ được hiển thị trên các trang này.

  1. Trong Solution Explorer, chọn Add -> New Item -> Web Form with Master Page có tên ProductList.aspx.

1-2


  1. Cửa sổ mới hiện ra, ta chọn Site.Master

1-3


  1. Thêm một trang tương tự tên ProductDetails.aspx
Cập nhật Bootstrap


Chúng ta sẽ dùng Bootstrap để thay đổi giao diện của Wingtip Toys như sau:

  1. Trong Solution Explorer, mở folder Content
  2. Đổi tên css thành bootstrap-original.css.
  3. Đổi tên min.css thành bootstrap-original.min.css.
  4. Nhấp chuột phải vào folder Content và chọn Open Folder in File Explorer, ta sẽ lưu file bootstrap vào đây.
  5. Vào trang
  6. Chọn một theme tùy thích vào down 2 file css và bootstrap.min.css về, copy vào folder Content đã mở, dán đè vào.
  7. Trong Visual Studio, nhấn vào Show All Files để hiện thị 2 file vừa thêm.
  8. Nhấp phải chuột vào file và chọn Include In Project.

1-4


Chỉnh sửa các điều hướng mặc định


Chúng ta có thể dễ dàng thay đổi các đường dẫn mặc định cho ứng dụng Web bằng cách sửa các thuộc tính trong Site.Master như sau:

  1. Mở trang Site.Master
  2. Thêm vào dòng sau đây trong <ul class=”nav navbar-nav”>:

<li><a runat="server" href="~/ProductList">Products</a></li>


1

<li><a runat="server" href="~/ProductList">Products</a></li>
  1. Sau khi thêm ta sẽ có cấu trúc sau đây:

<ul class="nav navbar-nav"> <li><a runat="server" href="~/">Home</a></li> <li><a runat="server" href="~/About">About</a></li> <li><a runat="server" href="~/Contact">Contact</a></li> <li><a runat="server" href="~/ProductList">Products</a></li> </ul>



1

2

3

4

5

6


<ul class="nav navbar-nav">

<li><a runat="server" href="~/">Home</a></li>

<li><a runat="server" href="~/About">About</a></li>

<li><a runat="server" href="~/Contact">Contact</a></li>

<li><a runat="server" href="~/ProductList">Products</a></li>

</ul>

Như bạn thấy, với mỗi cặp thẻ <li> chứa thẻ <a>, ta có thể thay đổi giá trị thuộc tính “href” trong đó để trỏ đến một trang cụ thể.

Note: Các dấu ngã(~) thường dùng để chỉ ra các đường dẫn bắt đầu từ gốc của project.

Thêm vào control Data để hiển thị dữ liệu khi điều hướng


Tiếp theo, ta sẽ thêm vào một control để hiển thị tất các categories từ DB. Mỗi category sẽ hoạt động như một link trỏ tới trang ProductList.aspx. Khi người dùng click vào một category link, họ sẽ được điều hướng tới trang Product và thấy các product tương ứng.

Ta sẽ dùng ListView để hiển thị các category trong DB. Các bước:

  1. Trong Site.Master, tìm thẻ <div> có id <div id=”TitleContent”> thêm vào dưới nó nội dung sau:

<div id="CategoryMenu" style="text-align: center"> <asp:ListView ID="categoryList" ItemType="DMWingtipToys.Models.Category" runat="server" SelectMethod="GetCategories" > <ItemTemplate> <b style="font-size: large; font-style: normal"> <a href="<%#: GetRouteUrl("ProductsByCategoryRoute", new {categoryName = Item.CategoryName})%>"> <%#: Item.CategoryName%> </a> </b> </ItemTemplate> <ItemSeparatorTemplate> | </ItemSeparatorTemplate> </asp:ListView> </div>



1

2

3

4

5

6

7

8

9

10

11

12

13


<div id="CategoryMenu" style="text-align: center">

<asp:ListView ID="categoryList"

ItemType="DMWingtipToys.Models.Category" runat="server" SelectMethod="GetCategories" >

<ItemTemplate>

<b style="font-size: large; font-style: normal">

<a href="<%#: GetRouteUrl("ProductsByCategoryRoute", new {categoryName = Item.CategoryName})%>">

<%#: Item.CategoryName%>

</a>

</b>

</ItemTemplate>

<ItemSeparatorTemplate> | </ItemSeparatorTemplate>

</asp:ListView>

</div>

Đoạn code sẽ hiển thị các Category từ DB. Ứng với mỗi Category trong Listview sẽ có tên kèm theo link trỏ đến ProductList.aspx với query-string chứa ID. Bằng việc cài đăt thuộc tính ItemType trong ListView, ta sẽ có một đối tượng strongly-typed Item, nhờ đó có thể truy cập các thuộc tính của Category bằng IntelliSense.

Liên kết dữ liệu từ Database


Trước khi hiển thị dữ liệu, ta cần liên kết với Database để lấy dữ liệu về.

  1. Vào Site.Master, nhấp phải chuột chọn View Code thêm vào 2 namespace:

using DMWingtipToys.Models; using DMWingtipToys.Logic;



using DMWingtipToys.Models;

using DMWingtipToys.Logic;
  1. Thêm vào đoạn code sau đây:

public IQueryable<Category> GetCategories() { var _db = new DMWingtipToys.Models.ProductContext(); IQueryable<Category> query = _db.Categories; return query; }



1

2

3

4

5

6


public IQueryable<Category> GetCategories()

{

var _db = new DMWingtipToys.Models.ProductContext();

IQueryable<Category> query = _db.Categories;

return query;

}

Đoạn mã trên sẽ chạy trong bất kì trang nào có sử dụng Master Page. Phương thức “GetCategories” trong thuộc tính SelectMethod của LisView sẽ chạy vào thời điểm thích hợp trong vòng đời của Page và tự động kết nối dữ liệu trả về.

Chạy ứng dụng và tạo Database


Trong Tut trước ta đã tạo một class khởi tạo tên “ProductDatabaseInitializer” và chỉ định nó trong “global.asax.cs”. EF sẽ tạo ra Database khi ứng dụng chạy lần đầu do phương thức Application_Start chứa trong “global.asax.cs” sẽ gọi class khởi tạo.Giá trị “|DataDirectory|” đại diện cho thư mục “App_Data” trong project, là nơi DB được lưu vào.

  1. Trong Solution Explorer, nhấp phải chuột vào aspx chọn Set As Start Page.
  2. Nhấn F5

1-5
Mở file Web.config và tìm đến “connection string”, ta thấy thuộc tính AttachDbFilename trỏ đến DataDirectory trong ứng dụng.

Tổng kết


Trong hướng dẫn này ta đã thêm một số giao diện, hình ảnh và điều hướng cho Web. Ngoài ra khi chạy trang Web, dữ liệu từ Database đã tạo trước đó sẽ được truy cập. Ta có thể thấy nội dung chứa trong bảng Products được hiển thị.


Sưu tầm & Tổng hợp
w: www.hanoiyeu.com
e: [email protected]