总结ASP.NET MVC Web Application中将数据显示到View中的几种方式

当我们用ASP.NET MVC开发Web应用程序的时候,我们都是将需要呈现的数据通过"Controllers"传输到"View"当中,怎么去实现,下面我介绍一下我在实际工作当中用到过的几种方式。

创建一个ASP.NET MVC Web Application

在Visual Studio中创建ASP.NET Web Application应用程序,在向导的下一个窗口中选择空的模板。

总结ASP.NET MVC Web Application中将数据显示到View中的几种方式

创建Model

接着我们在Models文件夹下创建一个Product类,用来传递数据。

1     public class Product
2     {
3         public int ProductID { get; set; }
4         public string ProductName { get; set; }
5         public decimal Price { get; set; }
6         public int Count { get; set; }
7         public string Description { get; set; }
8     }

创建Controller

接着在Controllers文件下创建一个Controller, 命名为"ProductController"。
总结ASP.NET MVC Web Application中将数据显示到View中的几种方式

创建View

然后我们在Views -> Product目录下创建一个View,命名为Index

总结ASP.NET MVC Web Application中将数据显示到View中的几种方式

到此,我们创建好了ModelViewController,在开始运行之前,我们需要更改一下默认路由配置。打开App_Start目录下的RouteConfig.cs文件,并更改默认路由如下:

 1     public class RouteConfig
 2     {
 3         public static void RegisterRoutes(RouteCollection routes)
 4         {
 5             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 6 
 7             routes.MapRoute(
 8                 name: "Default",
 9                 url: "{controller}/{action}/{id}",
10                 defaults: new { controller = "Product", action = "Index", id = UrlParameter.Optional }
11             );
12         }
13     }

好了,下面我们就正式开始实现数据从"Controller"到"View"的实现。

1. 使用ViewData。

ViewData是一个字典,它存放的是键值对。

打开新建好的ProductController.cs,使用using引入Product类所在的命名空间,在IndexAction里创建一个Product对象并且赋值给一个ViewData

using TransDataToView.Models;
 1         public ActionResult Index()
 2         {
 3             Product product = new Product
 4             {
 5                 ProductID = 1,
 6                 ProductName = "BMW X5",
 7                 Price = 1000000,
 8                 Count = 5,
 9                 Description = "BMW SUV"
10             };
11 
12             ViewData["Product"] = product;
13 
14             return View();
15         }

接着,我们打开新建好的Index View文件,对Controller里的ViewData数据进行接收处理。

 1 @using TransDataToView.Models
 2 @{
 3     Layout = null;
 4 }
 5 
 6 <!DOCTYPE html>
 7 
 8 <html>
 9 <head>
10     <meta name="viewport" content="width=device-width" />
11     <title>Index</title>
12 </head>
13 <body>
14     <div>
15         @{
16             var product = (Product)ViewData["Product"];
17         }
18         <h2>
19             Product ID: @product.ProductID <br />
20             Product Name: @product.ProductName <br />
21             Price: @product.Price <br />
22             Count: @product.Count <br />
23             Description: @product.Description
24         </h2>
25     </div>
26 </body>
27 </html>

 总结ASP.NET MVC Web Application中将数据显示到View中的几种方式

因为我们需要将ViewData数据转换成需要的Product对象数据,所以这里要引入Produdct类所在的命名空间,使用@符号,也就是Razor语法来引入,定义,赋值等操作。

2. 使用ViewBag。

ViewBag它跟ViewData一样,都是字典值,但它存放的不是键值对,而是dynamic动态类型,这是ASP.NET MVC3新增的部分。

同样我们在Index Action里将Proudct对象赋值给一个ViewBag

        public ActionResult Index()
        {
            Product product = new Product
            {
                ProductID = 1,
                ProductName = "BMW X5",
                Price = 1000000,
                Count = 5,
                Description = "BMW SUV"
            };

            ViewBag.Product = product;

            return View();
        }

同样,我们打开Index View文件,对Controller里的ViewBag数据进行接收处理。

 1 @{
 2     Layout = null;
 3 }
 4 
 5 <!DOCTYPE html>
 6 
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <title>Index</title>
11 </head>
12 <body>
13     <div>
14         <h3>
15             Product ID: @ViewBag.Product.ProductID <br />
16             Product Name: @ViewBag.Product.ProductName <br />
17             Price: @ViewBag.Product.Price <br />
18             Count: @ViewBag.Product.Count <br />
19             Description: @ViewBag.Product.Description
20         </h3>
21     </div>
22 </body>
23 </html>

可以看到ViewBag不需要转型直接就可以使用里面的数据了。

3. 使用TempData。

TempData也是字典,它的使用完全等同于ViewData,两者之间最大的差异是TempData对数据的保存是临时性的。也就是它请求后,数据就被清除,也就是只能通过一次Controller传递。通常用于Action之间的一次性传递,所以它一般不直接用于传递到View中。

我们增加一个名为"TempDataIndex"的Action

Controller:

 1         public ActionResult Index()
 2         {
 3             ViewData["Message"] = "This is a View Data Message.";
 4 
 5             if (TempData["Message"] != null)
 6                 ViewData["Message"] = TempData["Message"];
 7 
 8             return View();
 9         }
10 
11         public ActionResult TempDataIndex()
12         {
13             TempData["Message"] = "This is a Temp Data Message.";
14 
15             return RedirectToAction("Index");
16         }

View:

1     <div>
2         <h3>
3            @ViewData["Message"]
4         </h3>
5     </div>

我们运行程序。结果如下:
总结ASP.NET MVC Web Application中将数据显示到View中的几种方式

此时TempData数据为null,我们导航到/Product/TempDataIndex下,结果如下:

总结ASP.NET MVC Web Application中将数据显示到View中的几种方式

我们看到通过TempDataIndex的Action里,TempData["Message"]有了数据,然后转向了Index的Action方法里,所以TempData的值赋给了ViewData。这是我们刷新一下页面,结果如下:

总结ASP.NET MVC Web Application中将数据显示到View中的几种方式

4. 使用View(object)。

通过直接传递object数据到View中。

 1         public ActionResult Index()
 2         {
 3             Product product = new Product
 4             {
 5                 ProductID = 1,
 6                 ProductName = "BMW X5",
 7                 Price = 1000000,
 8                 Count = 5,
 9                 Description = "BMW SUV"
10             };
11 
12             return View(product);
13         }

那么在View文件中需要绑定Controller里传递的对象。

 1 @using TransDataToView.Models
 2 @model TransDataToView.Models.Product
 3 @{
 4     Layout = null;
 5 }
 6 
 7 <!DOCTYPE html>
 8 
 9 <html>
10 <head>
11     <meta name="viewport" content="width=device-width" />
12     <title>Index</title>
13 </head>
14 <body>
15     <div>
16         <h2>
17             Product ID: @Model.ProductID <br />
18             Product Name: @Model.ProductName <br />
19             Price: @Model.Price <br />
20             Count: @Model.Count <br />
21             Description: @Model.Description
22         </h2>
23     </div>
24 </body>
25 </html>

@model TransDataToView.Models.Product 意思就是绑定的是Product对象的Model,然后使用@Model.字段属性名来取值。

好了,本篇就先到此,希望对你有所帮助,谢谢!