asp.net MVC ViewData詳解

來源:互聯網
上載者:User

標籤:blog   http   使用   io   for   cti   html   代碼   

轉自:http://www.cnblogs.com/gaopin/archive/2012/11/13/2767515.html

控制器向視圖中傳值ViewData詳解

  1.將一個字串傳值到視圖中

         在action中我們將字串儲存在ViewData(或ViewBag [asp.net 3或以上才可用])中代碼如下:

         public ActionResult Index()
        {
            ViewData["str1"]= "這是一個字串";

             //也可以使用ViewBag來傳遞值

            ViewBag.str2="這是另外一個字串";

            return View();
        }

        在視圖中我們可以用下面代碼將字串顯示出來

        <h1>@ViewData["str1"]</h1>

        <h1>@ViewBag.str2</h1>

     2.將一個字串集合傳遞到視圖中

        public ActionResult Index()
        {
           List<string> str1= new List<string>();
            str1.Add("1111");
            str1.Add("2222");
            str1.Add("3333");
            ViewData["str"] = str1;

            return View();
        }

        在視圖中我們通過下面語句將str1的值顯示出來

       @foreach (var a in ViewData["str"] as List<string>)
         {
           @a
         }

       3.將一個datatable的值傳遞到視圖中

           public ActionResult Index()
            {

            DataTable newtable = new DataTable("d");
            newtable.Columns.Add("商品編號", typeof(string));
            newtable.Columns.Add("客戶編碼", typeof(string));
            DataRow NewRow = newtable.NewRow();
            NewRow["商品編號"] = "132323213434";
            NewRow["客戶編碼"] = "344223443244";
            newtable.Rows.Add(NewRow);
            DataRow SNewRow = newtable.NewRow();
            SNewRow["商品編號"] = "343432445456";
            SNewRow["客戶編碼"] = "454523432453";
            newtable.Rows.Add(SNewRow);
            ViewData["dt"]= newtable;
            return View();
            }

            在視圖中我們通過下面語句將dt的值顯示出來

            注意:在頂部要先加上:@using System.Data;

            <ul>
            @foreach(DataRow dr in (ViewData["dt"] as DataTable).Rows)
               {
                 <li>
                 @dr["商品編號"],@dr["客戶編碼"],
                 </li>
                }
              </ul>

聯繫我們

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