Cấp bậc tác giả:

TRAINING

[TUT]ASP.NET MVC 4 - Chia sẻ dữ liệu giữa Controllers và Views Components

Được viết bởi webmaster ngày 25/07/2015 lúc 04:54 PM
Tập trung vào việc làm thế nào để Chia sẻ dữ liệu giữa Controllers và Views Components
  • 0
  • 22556
Tải tệp tin: Click ở đây

[TUT]ASP.NET MVC 4 - Chia sẻ dữ liệu giữa Controllers và Views Components

Bài trước: 

[TUT]ASP.NET MVC 4 - Thiết kế layout với View Content Page, Master Page và User Control Page


Đã đính kèm Mock Project để tải về thực hành. Mọi thắc mắc liên hệ qua mail webmaster@dotnet.vn hoặc truy cập vào Face Page tại địa chỉ https://www.facebook.com/DotnetGroup

Mục tiêu:
- Tìm hiểu quan hệ giữa Action và View
- Tìm hiểu 2 khái niệm POST và GET
- Tìm hiểu một số đối tượng của ASP.NET và khai báo thay thế trong MVC
- Tìm hiểu phương thức RedirectToAction
- Tìm hiểu cách truyền giá trị từ Controller đến Views
- Hiểu thêm ViewBag, ViewData, TempDate
- Tìm hiểu cách truyền giá trị từ Views đến Controllers

POST
- Truyền giá trị từ client side đến server side thông qua hash table của trình duyệt
- <form name="form1" method="post">

GET
- Truyền giá trị từ client side đến server side thông qua query string của trình duyệt
- <form name="form1" method="get">
- Nhanh hơn POST

Chấp nhận 2 phương thức
- Accpet for POST: [AcceptVerbs(HttpVerbs.Post)]

VD:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult RestrictPostType(){
ViewData["Title"]= Request.HttpMethod;
return View();
}
- Accpet for GET: [AcceptVerbs(HttpVerbs.Get)]

VD:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult RestrictGetType(){
ViewData["Title"]= Request.HttpMethod;
return View();
}
Hai Action cho một View như sau
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult PostAndGet(){
ViewBag.Title= "Đây là Post";
return View();
}

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult PostAndGet(){
ViewBag.Title= "Đây là Get";
return View();
}

Làm ví dụ:
- Tạo trang PostAndGet.aspx trong thư mục Home
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
   Post And Get
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%using(Html.BeginForm()){ %>
    <table id="table1" style="width: 100%">
        <tr>
            <td colspan="2">View với 2 Action</td>
        </tr>
        <tr>
            <td>Keyword</td>
            <td>
                <%= Html.TextBox("Keyword") %>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
                <input id="Submit1" type="submit" value="Tìm kiếm" />&nbsp<%= ViewBag.Data %></td>
        </tr>
    </table>
    <%} %>
</asp:Content>
- Trong HomeController thêm hàm
[AcceptVerbs(HttpVerbs.Get)]
        public ActionResult PostAndGet()
        {
            ViewBag.Data = "Đây là Get";
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult PostAndGet(FormCollection collection)
        {
            ViewBag.Data = "Đây là Post";
            return View();
        }
- Chạy như hình
Lần đầu tiên

post-and-get-05.jpg

Nhấn Tìm kiếm sẽ xuất hiện "Đây là Post".

Đối tượng Request của HttpRequestBase
- Collection: Form.Get, QueryString.Get, Cookie, Server Variables, Headers
- Properties: RawUrl, UrlReferrer, Url, TotalBytes, HostName, HostAdress, InputStream

Đối tượng Response của HttpReponseBase
- Collection: Cookie, Headers
- Method: Redirect, SetCookie, AddHeader, AddCookie
- Properties: OutputStream, Charset, ContentType

Ví dụ
- Tạo thư mục Object trong thư mục Views
- Tạo tệp tin RequestForm.aspx trong thư mục Object sử dụng HomePage.Master
<%@ Page Language="C#" MasterPageFile="~/Views/MasterPages/HomePage.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    RequestForm
</asp:Content>

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

    <h2>RequestForm</h2>  <% using (Html.BeginForm("RequestForm", "Object", FormMethod.Post))
           { %>
    <table id="table1" style="width: 100%">
        <tr>
            <td>Email</td>
            <td><%= Html.TextBox("Email") %></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><%= Html.Password("Password") %></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
                <input id="Submit1" type="submit" value="submit" /><%= Html.ActionLink("Home","Index","Home") %></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
                <% if (ViewBag.Email != null)
                   { %>
                Email: <%=ViewBag.Email %><br />
                Password: <%=ViewBag.Password %>
                <%} %>
            </td>
        </tr>
    </table>
    <%} %>
</asp:Content>

- Tạo ObjectController.cs trong thư mục Controllers
[AcceptVerbs(HttpVerbs.Get)]
        public ActionResult RequestForm()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult RequestForm(string id)
        {
            string email = Request.Form.Get("Email");
            string password = Request.Form.Get("Password");
            ViewBag.Email = email;
            ViewBag.Password = password;
            return View();
        }

- Kết quả như sau:

Request-Form-06.jpg

Làm thêm ví dụ khác về Request QueryString:

- Tạo tệp tin RequestQueryString.aspx trong thư mục Object sử dụng HomePage.Master
 <%= Html.ActionLink("Request QueryString", "RequestQueryString", new { id="HCM"})%><br />
    <%= (String.IsNullOrEmpty(ViewBag.Id))?"":ViewBag.Id %>
- Tạo hàm sau trong ObjectController
public ActionResult RequestQueryString(string id)
        {
            ViewBag.Id = "Tham số nhận được: "+ id;
            return View();
        }
- Kết quả như màn hình:

Request-QueryString-07.jpg

Ví dụ tiếp theo về RequestServerVariables

- Tạo tệp tin RequestServerVariables.aspx trong thư mục Object sử dụng HomePage.Master
 <%= (String.IsNullOrEmpty(ViewBag.ServerName))?"":ViewBag.ServerName %>
- Tạo hàm sau trong ObjectController
public ActionResult RequestServerVariables(string id)
        {
            string text = "";
            foreach (string keyName in Request.ServerVariables.AllKeys)
            {
                if (!String.IsNullOrEmpty(keyName))
                    text = "keyName: " + Request.ServerVariables.Get(keyName) + "<br/>";
            }
            ViewBag.ServerName = text;

            return View();
        }
Sử dụng hàm trên để xem người dùng đang duyệt bằng trình duyệt nào, máy nào,...

- Kết quả như màn hình:

RequestServerVariables-08.jpg

Ví dụ tiếp theo về ResponseRedirect

- Tạo tệp tin ResponseRedirect.aspx trong thư mục Object sử dụng HomePage.Master

- Tạo hàm sau trong ObjectController
public ActionResult ResponseRedirect()
        {
            string email = Request.Form.Get("Email");
            string password = Request.Form.Get("Password");
            if (String.IsNullOrEmpty(email)&& Request.HttpMethod=="POST")
                Response.Redirect("http://dotnet.edu.vn");
            
            return View();
        }
//Kiểm tra email đã nhập vào chưa, và thực hiện phương thức POST, nếu không khi load trang sẽ tự động nhảy sang trang điều hướng mà chưa kịp làm gì tại trang hiện hành.

Đối tượng Session
- Session.Add("Name", objValue) // Sử dụng để gán
- Object obj = Session["Name"]
- Session.Timeout = numberOfMinutes; // Chu kỳ sống của session
- String sessionId = Session.SessionID;
- Session.Remove(xóa 1 session), Session.RemoveAll(xóa tất cả), Session.RemoveAt(tại 1 session), Session.Abandon(hủy tất cả các session)

Đối tượng RedirectToAction
RedirectToAction(String actionName, String controllerName): Điều hướng đến controller cụ thể
VD: return RedirectToAction("/MyAccount"); // Views: MyAccount
RedirectToAction(String actionName, String controllerName, new {@id=value, @xyz=?}): Điều hướng đến controller cụ thể có giá trị tham số truyền vào

Đối tượng Cookie
Tương tự như Session
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult SetCookie()
{
return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SetCookie(FormCollection collection)
{
string email = Convert.ToString(Session["Email"]);
HttpCookie httpCookie = new HttpCookie("dotnetgroup",email);
Response.Cookie.Add(httpCookie)
return RedirectToAction("GetCookie");
}

public ActionResult GetCookie()
{
HttpCookie httpCookie = Request.Cookies.Get("dotnetgroup");
string email =  httpCookie.Value;
ViewBag = email;
return View();
}
Truyền giá trị từ Controller sang View

pass-controller-to-view-9.jpg

Đối tượng ViewData
- Có sẵn từ phiên bản đầu tiên của MVC
- Chứa đựng bất kỳ kiểu dữ liệu nào trong đó có name-value 
- Cú pháp:
Trong Controller: ViewData["KeyName"]="Value"
Trong View: <div><%=ViewData["KeyName"]%></div>

VD:
public ActionResult ViewDataObject(){
ViewData["WelcomeMessage"] = "This is ViewData object";
ViewData["Date"] = DateTime.Now.Date;
ViewData["Student"] = new Student();
Account account = new Account();
ViewData["Name"] = account.Name;
}

Chú ý: Nếu là một Object thì phải ép kiểu
<%=(MvcApplication.Models.Employee)ViewData["Employee"]).Id%>

Đối tượng ViewBag
Tương tự như ViewData, nhưng cho phép gán cài đặt thuộc tính dễ hơn như ViewBag.Key= objectValue; thay vì sử dụng ngoặc []
Và việc gọi đối tượng trong View cũng trở nên đơn giản bằng cách:
<%= ViewBag.KeyName.propertyName%>
Đây được gọi là strongly typed

ViewData và ViewBag chỉ có hiệu lực sử dụng trong 1 action của View, không thể mang giá trị từ action này sang action khác(Session/Cookie).

Đối tượng TempData
- Sử dụng để mang giá trị từ action này sang action khác chỉ 1 lần thôi.
- Cú pháp:
TempData["Name"] = objectValue;
<div><%= TempData["Name"] %></div>

bi-quyet-login-10.jpg

Truyền giá trị từ View sang Controller

Cú pháp FormCollection
public ActionResult Login(FormCollection collection){
string userName = collection.Get("HTMLTag")
}

Cú pháp Request
public ActionResult Login()
{
var collection = Request.Form;
string userName = collection.Get("Textbox1")
}

Làm quen với Lớp trong Models

- Tạo class Employee trong Models
string name="DOTNET GROUP";
        string email="Webmaster@dotnet.vn";

        public string Email
        {
            get { return email; }
            set { email = value; }
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public void Save(){}
- Tạo thư mục ViewToController trong Views
- Tạo ObjectModelParametter.aspx
<h2>ObjectModelParametter</h2>

         <% using (Html.BeginForm())
           { %>
        <table id="table1" style="width: 100%;">
            <tr>
                <td>Name</td>
                <td><%= Html.TextBox("Name") %></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><%= Html.TextBox("Email1") %></td>
            </tr>
            <tr>
                <td>
                    <input id="Submit1" type="submit" value="submit" /></td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td>Name <%= (String.IsNullOrEmpty(ViewBag.Name) ?"":ViewBag.Name) %></td>
                <td></td>
            </tr>
             <tr>
                <td>Email <%= (String.IsNullOrEmpty(ViewBag.Email) ? "": ViewBag.Email) %></td>
                <td></td>
            </tr>
        </table>
    <%} %>
- Tạo ViewToControllerController.cs trong Controllers
 [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ObjectModelParametter()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ObjectModelParametter(Employee employee)
        {
            ViewBag.Name = employee.Name;
            ViewBag.Email = employee.Email;
            ViewBag.Employee = employee;
            employee.Save();
            return View();
        }
LINQ và ADO.NET Entity
- Cú pháp:
public ActionResult Account(ClassName className){}
- VD: 
public ActionResult Account(Student student){
context.AddToStudents(stduent)
context.SaveChanges();
}
Làm việc với SQL Server Database
* ADO.NET Data Providers
- SqlConnection: ConnectionString
- SqlCommand: Command Text
- SqlDaraAdapter: Fill và Update dữ liệu
- SqlDataReader: Readly, NextResult

SQL Server => DataSet, DataTable, DataRow

* LINQ to SQL(2008/2010): Thao tác dữ liệu với SQL Server bằng LINQ
* ADO.NET Entity(2010): Thao tác dữ liệu với SQL Server bằng ADO.NET Entity

Bài tiếp theo: Enhance Data Viewing by Strong Type, View Type and HTML tags

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML