1. 程式人生 > >MVC教程四:Controller向View傳值的幾種方式

MVC教程四:Controller向View傳值的幾種方式

一、通過ViewData傳值

MVC從開始版本就一直支援使用ViewData將Controller裡面的資料傳遞到View。ViewData定義如下:

從上面的截圖中可以看出,ViewData裡面存的是字典型別的資料,在檢視ViewDataDictionary的定義:

注意:ViewDataDictionary繼承自IDictionary等介面,所以ViewData裡面的Value值型別是object的,使用的時候需要進行型別轉換。

Controller程式碼如下:

using MVCPassValue.Models;
using System;
using System.Collections.Generic;
using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCPassValue.Controllers { public class ViewDataDemoController : Controller { // GET: ViewDataDemo public ActionResult Index(int? id) { //1、將字串傳遞到View ViewData["Other"] = "通過ViewData傳遞字串
"; // 2 ViewData.Add(new KeyValuePair<string, object>("Id", id ?? -1)); //3 ViewData.Add("name", "tom"); //4、將集合傳遞到View ViewData["Student"] = new List<Student>() { new Student { ID
= 1, Name = "唐僧", Age = 34, Sex = "", Email = "[email protected]" }, new Student { ID = 2, Name = "孫悟空", Age = 635, Sex = "", Email = "[email protected]" }, new Student { ID = 3, Name = "白骨精", Age = 4532, Sex = "", Email = "[email protected]" } }; return View(); } } }

 

 View檢視如下:

@using MVCPassValue.Models;
@{
    ViewBag.Title = "Index";
}
@{
    // 這裡是使用的Razor語法,寫的C#程式碼
    var stuViewData = ViewData["Student"] as List<Student>;//ViewData的value值是object型別的,這裡需要進行型別轉換
    var other = ViewData["Other"];
}

<div class="jumbotron">
    <p>
        <div style="background-color:darkgreen">
            <div>
                Controller通過ViewData向View傳遞資料
            </div>
            <div>
                1、傳遞字串 other:@other;
            </div>
            <div>
                2、傳遞字串 Id:@ViewData["Id"];
            </div>
            <div>
                3、傳遞字串 name:@ViewData["name"];
            </div>
            <div>
                4、傳遞集合
                @foreach (var item in stuViewData)
                {
                    <div>
                        ID:@item.ID&nbsp;&nbsp;Name:@item.Name&nbsp;&nbsp;Age:@item.Age&nbsp;&nbsp;Sex:@item.Sex&nbsp;&nbsp;Email:@item.Email
                    </div>
                }
            </div>
        </div>
    </p>
</div>

 執行結果:

二、通過ViewBag傳值

ViewBag是在MVC3中出現的,ViewBag是動態(dynamic)型別的。

 Controller程式碼:

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

namespace MVCPassValue.Controllers
{
    public class ViewBagDemoController : Controller
    {
        // GET: ViewBagDemo
        public ActionResult Index(int? id)
        {
            //1、將字串傳遞到View
            ViewData["Other"] = "通過ViewData傳遞字串";

            // 2
            ViewData.Add(new KeyValuePair<string, object>("Id", id ?? -1));

            //3
            ViewData.Add("name", "tom");
            //4、將集合傳遞到View
            ViewData["Student"] = new List<Student>()
             {
               new Student
               {
                 ID = 1,
                 Name = "唐僧",
                 Age = 34,
                 Sex = "",
                 Email = "[email protected]"
               },
               new Student
               {
                 ID = 2,
                 Name = "孫悟空",
                 Age = 635,
                 Sex = "",
                 Email = "[email protected]"
               },
               new Student
               {
                 ID = 3,
                 Name = "白骨精",
                 Age = 4532,
                 Sex = "",
                 Email = "[email protected]"
               }
             };


            #region 2、通過ViewBag傳值
            ViewBag.name = "ViewBag";
            ViewBag.Stu1 = new Student()
            {
                ID = 5,
                Name = "沙悟淨",
                Age = 567,
                Sex = "",
                Email = "[email protected]"
            };
            #endregion
            return View();
        }
    }
}

  Index檢視程式碼:

@using MVCPassValue.Models;
@{
    ViewBag.Title = "Index";
}
@{
    var stuViewData = ViewData["Student"] as List<Student>;//ViewData的value值是object型別的,這裡需要進行型別轉換
    var other = ViewData["Other"];
}

@{
    var name = ViewBag.name;
    var stu = ViewBag.Stu1;//ViewBag是dynamic型別的,使用的時候不需要進行型別轉換
    var stuList = ViewBag.Student;
}

<div class="jumbotron">
    <p>
        <div style="background-color:darkgreen">
            <div>
                Controller通過ViewData向View傳遞資料
            </div>
            <div>
                傳遞字串 ViewData["name"]:@ViewData["name"];
            </div>
        </div>
    </p>

    <p>
        <div style="background-color:crimson">
            <div>
                Controller通過ViewBag向View傳遞資料
            </div>
            <div>
                1、傳遞字串 ViewBag.name:@name;
            </div>
            <div>
                2、輸出stu
                <div>
                    ID:@stu.ID&nbsp;&nbsp;Name:@stu.Name&nbsp;&nbsp;Age:@stu.Age&nbsp;&nbsp;Sex:@stu.Sex&nbsp;&nbsp;Email:@stu.Email
                </div>
                3、輸出stuList
                @foreach (var item in stuList)
                {
                    <div>
                        ID:@item.ID&nbsp;&nbsp;Name:@item.Name&nbsp;&nbsp;Age:@item.Age&nbsp;&nbsp;Sex:@item.Sex&nbsp;&nbsp;Email:@item.Email
                    </div>
                }
            </div>
        </div>
    </p>
</div>

 執行結果;

看了上面的執行結果,你可能會提出如下的兩個疑問:

1、Controller裡面沒有定義ViewBag.Student,為什麼在這裡可以使用呢?

這是因為ViewBag是從MVC3版本才開始出現的,為了相容以前的ViewData,所以這裡雖然沒有定義ViewBag.Student,但是ViewBag可以使用ViewData裡面定義的Student。

2、ViewData["name"]和ViewBag.name的值是一樣的

在控制器裡面明明設定的兩個值是不同的,但是為什麼這裡都變成一樣的了呢?這是因為ViewData和ViewBag的屬性是重疊的,兩者都是字典型別的,一切以後面定義的屬性為準,即後面定義的會覆蓋前面定義的。

三、通過TempData傳值

先來看看下面的程式碼:

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

namespace MVCPassValue.Controllers
{
    public class TempDataDemoController : Controller
    {
        // GET: TempDataDemo
        public ActionResult Index()
        {
            ViewData["Name"] = "tom";
            ViewBag.Name = "Jon";
            TempData["Name"] = "Andi";
            TempData["Stu"] = new Student()
            {
                ID = 5,
                Name = "沙悟淨",
                Age = 567,
                Sex = "",
                Email = "[email protected]"
            };
            return View();
        }
    }
}

 

index檢視程式碼:

@using MVCPassValue.Models;
@{
    ViewBag.Title = "Index";
}
@{
    var stu = TempData["Stu"] as Student;
}

<div class="jumbotron">
    <p>
        <div style="background-color:darkgreen">
            <div>
                傳遞字串 ViewData["Name"]:@ViewData["Name"];
            </div>
        </div>
    </p>

    <p>
        <div style="background-color:crimson">
            <div>
                1、傳遞字串 ViewBag.Name:@ViewBag.Name;
            </div>
        </div>
    </p>
    <p>
        <div style="background-color:crimson">
            <div>
                1、傳遞字串 TempData["Name"]:@TempData["Name"];
            </div>
            2、輸出stu
            <div>
                ID:@stu.ID&nbsp;&nbsp;Name:@stu.Name&nbsp;&nbsp;Age:@stu.Age&nbsp;&nbsp;Sex:@stu.Sex&nbsp;&nbsp;Email:@stu.Email
            </div>
        </div>
    </p>
</div>

 允許結果:

從上面的結果中可以看出:TempData的屬性值不會覆蓋上面定義的屬性值。那TempData還有什麼作用呢?在看下面的程式碼:

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

namespace MVCPassValue.Controllers
{
    public class TempDataDemoController : Controller
    {
        // GET: TempDataDemo
        public ActionResult Index(int? id)
        {
            ViewData["Name"] = "tom";
            ViewBag.Name = "Jon";
            TempData["Name"] = "Andi";
            TempData["Stu"] = new Student()
            {
                ID = 5,
                Name = "沙悟淨",
                Age = 567,
                Sex = "",
                Email = "[email protected]"
            };

            if (id == null)
                return RedirectToAction("TempDataTest");
            else
                return View();
        }

        public ActionResult TempDataTest()
        {
            return View();
        }
    }
}

 TempDataTest檢視程式碼:

@using MVCPassValue.Models;
@{
    ViewBag.Title = "TempDataTest";
}
@{
    var stu = TempData["Stu"] as Student;
}

<h2>TempDataTest</h2>
<h3>ViewData["id"]:@ViewData["Id"]</h3>
<h3>ViewData["Name"]:@ViewData["Name"]</h3>
<h3>TempData["Name"]:@TempData["Name"];</h3>
<h3>ID:@stu.ID&nbsp;&nbsp;Name:@stu.Name&nbsp;&nbsp;Age:@stu.Age&nbsp;&nbsp;Sex:@stu.Sex&nbsp;&nbsp;Email:@stu.Email</h3>

 執行結果:

 

你會發現這時ViewData取不到資料了,只有TempData可以取到資料,可以得出TempData和ViewData、ViewBag的區別:

TempData是基於session儲存的,單次請求資料不丟失(ViewData和ViewBag會丟失),後臺跨頁面傳值,只能用一次

四、Model傳值

controller程式碼:

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

namespace MVCPassValue.Controllers
{
    public class ModelDemoController : Controller
    {
        // GET: ModelDemo
        public ActionResult Index()
        {
            return View(new Student()
            {
                ID = 5,
                Name = "沙悟淨",
                Age = 567,
                Sex = "",
                Email = "[email protected]"
            });
        }
    }
}

 index檢視程式碼:

@{
    ViewBag.Title = "Index";
}
@Model Student;

<h2>Index</h2>
<h3>ID:@Model.ID</h3>
<h3>Name:@Model.Name</h3>
<h3>Age:@Model.Age</h3>
<h3>Sex:@Model.Sex</h3>
<h3>Email:@Model.Email</h3>

 執行結果: