MVC控制器向View視圖傳值的三種方法

來源:互聯網
上載者:User

標籤:

首先建立一個MVC的項目,其中需要一個控制器(TestController),三個視圖(index,edit,detail)

1、項目結構如下:

 

2、控制器向視圖傳值的三種方法

1)提供視圖模型對象(直接把對象放在View裡面)

2)通過VewBag傳遞資料

3)通過ViewData傳遞資料

 

3、控制器源碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCTest.Controllers
{
    public class TestController : Controller
    {  
        /// <summary>
        /// 1、提供視圖模型對象
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            DateTime date = DateTime.Now;
            //一個對象作為View方法的參數傳遞給視圖
            return View(date);
        }
        /// <summary>
        /// 2、使用ViewBag(視圖包)傳遞資料
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit() {
            //ViewBag 允許在一個動態對象上定義任意屬性,並在視圖中訪問它.這個動態對象可以通過Controller.ViewBag屬性訪問它.
            ViewBag.Name = "及時雨";
            ViewBag.Age = "21";
            ViewBag.Hobby = "打籃球,看書等";
            ViewBag.StrDate = DateTime.Now;
            return View();
        }
        /// <summary>
        /// 3、 使用View Data傳遞資料
        /// </summary>
        /// <returns></returns>
        public ActionResult Detail() {
            //在MVC3.0之前,主要是通過這種方式傳遞資料,它是通過用 ViewDataDictionary類實現的,而不是動態對象.
            //ViewDataDictionary類是類似標準"鍵/值"集合,並通過Controller類的ViewData屬性進行訪問的.這個方法,在視圖中需要對對象進行轉換.
            ViewData["Message"] = "Hello,EveryOne!";
            ViewData["Date"] = DateTime.Now;
            return View();
        }
    }
}


4、視圖的調用

1)index視圖

2)edit視圖

3)detail視圖

5、頁面的顯示效果

1)index頁面

2)edit頁面

3)detail頁面

Ps: 視圖向控制器傳值,一般是通過ajax請求控制器的方法,請求是將參數帶到控制器方法參數裡面

MVC控制器向View視圖傳值的三種方法

聯繫我們

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