ASP.NET MVC 學習二、從Controller傳遞數據到View

 

 參考:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-viewhtml

一,Controller 中的ActionResult方法會用一個View Template生成HTML頁面反饋到瀏覽器中:數據庫

1,修改Index方法以下瀏覽器

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

2,在Index 方法中右鍵,添加View視圖,Views視圖下的HelloWorld文件夾中生成了對應的Index.cshtml文件mvc

                  

3,打開index.cshtml文件,並添加一行html代碼以下:asp.net

@{ViewBag.Title = "Index";}
<h2>Index</h2>
<p>Hello from our View Template!</p>

4,右擊index.cshtml,頁面探測器Page Inspector打開(ctrl+K,ctrl+G),可看到生成的html頁面,Ctrl+F5刷新(http://localhost:9898/HelloWorld/Index ),咱們看到雖然Controller中的Index方法就只是簡簡單單的 Return View(),並無特別指定要輸出哪一個View Page,可是MVC默認會調用Index.cshtml.這就是MVC中的Hard-Code.佈局

以上頁面的運行,後須要理解頁面具體是怎麼運行出來的:從一個ActionResult方法指向View頁面顯示在瀏覽器中性能

URL→Controller 中的ActionResult方法→ActionResult方法名對應的Views中同名的視圖測試

 

二,瞭解_Layout.cshtml頁面url

注意到:上面所顯示的這個index.cshtml的頁面標題倒是」index-個人ASP.NET MVC…」,這是由於index.cshtml調用了_layout.cshtml模板spa

下面咱們來改一下View的模板頁面:/Views/Shared/_Layout.cshtml

Layout.cshtml 佈局頁面,就至關於一個容器,能夠把layout頁面的佈局以及內容套用於其它頁面。

Layout.cshtml中的@RenderBody()是佔位符,這裏代替其它調用Layout.cshtml的頁面內容,例如:咱們打開連接http://localhost:9898/Home/About 這時候,about.cshtml的內容就嵌套到了layout.cshtml中的@renderBody()的位置

改變Layout中的Title: ViewBag的值加」-Movie App」

<title>@ViewBag.Title - Movie App</title>

子頁面:

@{ ViewBag.Title = "Movie List";}

<h2>My Movie List</h2>

 ViewBag.Title能夠在layout.cshtml和index.cshtml之間進行傳值,頁面運行之後能夠看到title:

 

 

三,傳輸數據從Controller到View:

Controller Classes 在瀏覽器請求URL的時候被調用

Controller Class中的代碼就是處理瀏覽器請求,從數據庫中檢索數據,最終調用相應的View顯示在瀏覽器中

View中不該該直接有與數據交互和業務邏輯的部分,View只能夠接收從Controller傳遞過來的數據

這種分離模式,能夠讓你的代碼簡潔,測試性能以及可維護性能更高

 

ViewBag 是一個Dynamic Object,這意味着你能夠傳遞任何類型的數據給它。

ViewBag 沒有定義任何屬性,直到你賦值給它。

 

ASP.NET MVC model binding system 會自動映射URL中的參數到Controller的方法的參數中。更新Controller中的Welcome方法以下:

   public ActionResult Welcome(string name, int numTimes)
        {
            ViewBag.Message = "Hello " + name;
            ViewBag.NumTimes = numTimes;
            return View();
        }

 運行一下,看到數據傳遞過程:

 http://localhost:9898/HelloWorld/Welcome?name=Spring&numtimes=10(URL)

              url請求傳遞到HelloWorldController的Welcome方法中          

  public ActionResult Welcome(string name, int numTimes)

        {

            ViewBag.Message = "Hello " + name;

            ViewBag.NumTimes = numTimes;

            return View();

        }

                  Welcome中的方法的數據傳遞到View頁面中

 

<ul>

    @for (int i = 1; i < ViewBag.NumTimes; i++)

    { 

        <li>@ViewBag.Message</li>

    }

</ul>

.cshtml顯示效果:

相關文章
相關標籤/搜索