MVC總結--資料傳遞

來源:互聯網
上載者:User

標籤:mvc   資料傳遞   

  • View—>Controller

      1.傳統方式,Get方式提交,在Controller中獲得用戶端請求:

      string Name = Request["name"];

      string Id=Request .QueryString ["id"];

      2.超連結方式

      在超連結中傳參,改進了原來的<a></a>

      <%:Html .ActionLink ("連結","Index","Home",new{id="1",name="Jim"}) %>

      上面的new{},就是在傳遞一個參數集合,以這種方式傳過來的參數Controller如何接收呢?

      假如是連結到Index頁面,那麼在Controller中的Index方法的參數中,這樣寫,這裡的參數名稱一定要和上述的參數名稱一致。

       public ActionResult Index(intid,string name)

       {

              return View();

       }

      也可以通過實體來獲得

      public ActionResult Index(UserInfo user)

      {

              return View();

      }

      只是,實體中的屬性也必須對應著:

      public class UserInfo

      {

              public string id { get; set; }

              public stringname { get; set; }

      }

     3.Post:獲得用戶端提交的資料:Request.Form

     4.在用戶端建立表單,在Controller中獲得表單集合FormCollection

     public ActionResult Index(FormCollection form1)

  • Controller—>View

     1.傳統方式,直接輸出:

     Response.Write(form1.Count );

     return Content("ok");

  • Controller<—>View

      1.通過ViewData

      ViewData是字典容器,它是key/Value鍵值集合

      在Controller中:

      ViewData["key"]

      在View中:

      <%=ViewData["key"]%>

      <%:ViewData["key"]%>

      或者讓某個控制項顯示ViewData中的資料

      <%=Html .TextBox ("txtName") %>

      只要key值相同,Controller和View中的ViewData中的資料就可以互相傳遞。

      2.強型別頁面,設定視圖模型

      弱類型頁面傳遞的資料,沒有限制,而強型別頁面規定了該頁面傳遞的資料類型--指定的某個模型(Model),可以使傳遞的資料準確,安全。為了讓它們之間資料傳遞通暢無阻,需要我們在Controller中設定ViewData.Model類型。

      在頁面上我們也要設定:

       <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo1.Models.TDepartment>" %>

                               

      然後在頁面中就可以獲得模型中具體欄位,<%: Html.DisplayNameFor(model => model.txtName) %>

      這裡"model"就是一個變數名,可以任意命名,因為在整個頁面已經規定了類型了,所以也可以寫成。

      <%: Html.DisplayNameFor(m => m.txtName) %>

  • 總結

      MVC中的資料傳遞看起來方便,安全,當然也有很多約束,如一些參數名稱的對應,除了以上方式,還有ViewBag等傳遞資料的方式,需要我們在實際應用中來比較它們各自的優劣。

MVC總結--資料傳遞

聯繫我們

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