ASP.NET MVC中Controller與View之間的資料傳遞總結

來源:互聯網
上載者:User

在ASP.NET MVC中,經常會在Controller與View之間傳遞資料,因此,熟練、靈活的掌握這兩層之間的資料傳遞方法就非常重要。本文從兩個方面進行探討:

Ø ControllerView傳遞資料

Ø ViewController傳遞資料

 

一、ControllerView傳遞資料

1.       使用ViewData傳遞資料

我們在Controller中定義如下:

ViewData[“Message”] = “Hello word!”;

然後在View中讀取Controller中定義的ViewData資料,代碼如下:

<% = Html.Encode(ViewData[“Message”]) %>

2.       使用TempData傳遞資料

我們在Controller中定義如下:

TempData[“Message”] = “Hello word!”;

然後在View中讀取Controller中定義的TempData資料,代碼如下:

<% = Html.Encode(TempData [“Message”]) %>

3.       使用Model傳遞資料

使用Model傳遞資料的時候,通常在建立View的時候我們會選擇建立強型別View如所示:

建立強型別的View以後,View的第一行代碼如下所示:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcInduction.Models.People>" %>

 

<MvcInduction.Models.People>就代表了這個View使用的Model為“MvcInduction.Models.People”

 

總結:

1.         ViewData與TempData方式是弱類型的方式傳遞資料,而使用Model傳遞資料是強型別的方式。

2.         ViewData與TempData是完全不同的資料類型,ViewData資料類型是ViewDataDictionary類的執行個體化對象,而TempData的資料類型是TempDataDictionary類的執行個體化對象。

3.         TempData實際上儲存在Session中,控制器每次執行請求時都會從Session中擷取TempData資料並刪除該Session。TempData資料只能在控制器中傳遞一次,其中的每個元素也只能被訪問一次,訪問之後會被自動刪除。

4.         ViewData只能在一個Action方法中進行設定,在相關的視圖頁面讀取,只對當前視圖有效。理論上,TempData應該可以在一個Action中設定,多個頁面讀取。但是,實際上TempData中的元素被訪問一次以後就會被刪除。

 

二、ViewController傳遞資料

在ASP.NET MVC中,將View中的資料傳遞到控制器中,主要通過發送表單的方式來實現。具體的方式有:

1.         通過Request.Form讀取表單資料

我們在View層做如下定義:

<% using (Html.BeginForm("ActionName", "ControllerName"))

       { %>

    UserName:<% Html.TextBox("UserName"); %>

    Password:<% Html.TextBox("Password"); %>

<%} %>

注意:ActionName為對應的Action名,ControllerName為對應的Controller名稱

然後在Controller層,通過Request.Form讀取表單資料的代碼如下所示:

[AcceptVerbs(HttpVerbs.Post)]

        public ActionResult ActionName()

        {

            string username = Request.Form["UserName"];

            string password = Request.Form["Password"];

            return View();

}

2.       通過FormCollection讀取表單資料

我們在View層做如下定義:

<% using (Html.BeginForm("ActionName", "ControllerName"))

       { %>

    UserName:<% Html.TextBox("UserName"); %>

    Password:<% Html.TextBox("Password"); %>

<%} %>

然後在Controller層,通過FormCollection讀取表單資料的代碼如下所示:

[AcceptVerbs(HttpVerbs.Post)]

        public ActionResult ActionName(FormCollection formCollection)

        {

            string username = formCollection["UserName"];

            string password = formCollection["Password"];

            return View();

        }

 3.       自訂資料繫結

自訂資料繫結的方法如下:建立一個自訂資料繫結類,讓這個類繼承自IModelBinder,實現該介面中的BindModel方法。
由於寫作倉促,代碼未列出。敬請見諒。
 

總結:雖然我們可以通過Request.Form或FormCollection方式讀取表單資料,可是通常這兩種方式都比較繁瑣,在強型別View的情況下,我們通常會使用Controller 基類的內建方法UpdateModel(),該方法支援使用傳入的表單參數更新對象的屬性,它使用反射機制來解析對象的屬性名稱,接著基於用戶端傳入的參數值自動賦值給對象相關屬性。

以下是我寫的一個Demo的一段使用UpdateModel的代碼例子:

使用UpdateModel()的代碼例子[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            //Users user = userRepository.GetUser(id);
            //user.UserName = Request.Form["UserName"];
            //user.Password = Request.Form["Password"];
            //user.Telephone = Request.Form["Telephone"];
            //user.Address = Request.Form["Address"];
            //上述方法有一點繁瑣,特別是增加異常處理邏輯之後。一個更好的方法是使用Controller 基類的內建方法UpdateModel()。該方法支援使用傳入的表單參數更新對象的屬性,它使用反射機制來解析對象的屬性名稱,接著基於用戶端傳入的參數值自動賦值給對象相關屬性。
            Users user = userRepository.GetUser(id);
            string[] allowedProperties = new[] { "UserName", "Password", "Telephone", "Address" };
                UpdateModel(user, allowedProperties);
                userRepository.Save();

                return RedirectToAction("Details", new { id = user.ID });
        }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.