Quantcast
Channel: MEPO Forum - 程式設計
Viewing all articles
Browse latest Browse all 99

Learn MVC Project in 7 days – Day 2 – Lab 3 – Using ViewData (no replies)

$
0
0
=======================================================


Learn MVC Project in 7 days – Day 2


=======================================================

Lab 3 – Using ViewData
Lab 3 – 使用「ViewData」)

=======================================================

目的:
(一)了解 Action Method 與 View 之間 傳遞 資料 的其中一種方法 - ViewData
(二)簡介 Razor 的用法

=======================================================


步驟:(詳見原文)

(一)建立一個 Model Class (模型類別?)

在 Model 資料夾底下 建立一個 Class 叫做 Employee 如下:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Salary { get; set; }
}


(二)在 Controller 裡,使用 該 Class

在 Action Method GetView() 裡面,建立一個 Employee object (物件) 如下

Employee emp = new Employee();
emp.FirstName = "Sukesh";
emp.LastName="Marla";
emp.Salary = 20000;


當然,如果可以在程式最上面 使用下列 using 敘述,使用該 class 的時候,就不用打一大串名字

using WebApplication1.Models;


(三)建立 ViewData 物件,並傳給 View

將 Employee 物件存到 ViewData裡面,如下:

ViewData["Employee"] = emp;
return View("MyView");




(四)在 View 裡面,將 Employee 的資料印出來

加入程式碼如下:

@{ WebApplication1.Models.Employee emp=(WebApplication1.Models.Employee) ViewData["Employee"]; } Employee Details
Employee Name : @emp.FirstName@emp.LastName
Employee Salary: @emp.Salary.ToString("C")

(五)測式結果:

在網址列鍵入:localhost/Test/GetView

結果如下:


https://www.codeproject.com/KB/aspnet/897559/E.png


=======================================================

討論:

(一)

Viewing all articles
Browse latest Browse all 99

Trending Articles