iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 10
1
Modern Web

打net core肉飯系列 第 10

[2020鐵人賽] Day10 - 檢視(View)

由於以前曾經寫過,部分內容會延續以前的內容。
今天來設定MVC中的View,View可以說是用於畫面的顯示,可以再裡面寫HTML、引用CSS、JS等等...

Controller.cs

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

其中Index上述方法來產生 HTML 回應給瀏覽器。
如下圖點選,可產生index.cshtml檔案
https://ithelp.ithome.com.tw/upload/images/20181019/20111766sPxKrOJWSb.png

會產生如下的程式碼

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>Hello from our View Template!</p>

其頁面顯示如下...
https://ithelp.ithome.com.tw/upload/images/20181019/20111766rJU67x3QQC.png

基本設定完成,接著介紹幾個常用的寫法..
使用@ 可以在cshtml裡面寫一些C#的程式
例如我們可以在index.cshtml寫C#的foreach並且參雜html語法作顯示

<ul>
@foreach(var item in (SomeType)ViewBag.dataList){
  <li>@item.data</li>
}
</ul>

如此就可以將後端的dataList綁到前端顯示出來,覺得相當好用,當然也可以用JS寫就好。

這邊分享一些在view前端常用的一些東西
Partial View
-當成可重複使用的View
-主要類似WebForm時代的UserControl

做出以下的設定
https://ithelp.ithome.com.tw/upload/images/20181020/20111766j37qsiRaQQ.png

使用Render的方式取得PartialView,達到共用的效果...
https://ithelp.ithome.com.tw/upload/images/20181020/20111766OthwKJxIT0.png

Razor
是非常好用的,前面一篇有稍微提到,這邊引用MVC美學的一段話
https://ithelp.ithome.com.tw/upload/images/20181020/20111766AQaDNWn6us.png
https://ithelp.ithome.com.tw/upload/images/20181020/20111766wwncBtfOkZ.png
簡單來說就是可以在前端寫入後端的程式

ViewData & ViewBag
我覺得在從後端傳遞資料,在不透過model回傳的情況下,這兩個算是十分好用的。

  • ViewBag:屬於Dynamic,意即compile time不檢查是否有錯,你可以ViewBag.Name.xxx(呼叫任何Function也是可以過的)
    • 使用方式(Controller) - ViewBag.Name = "Scott"
    • 使用方式(View) - @ViewBag.Name
  • ViewData:是一個dictionary物件
    • 使用方式(Controller) - ViewData["Name"] = "Scott"
    • 使用方式(View) - @ViewData["Name"]

簡單練習
剛剛觀念解釋完之後,來處理DataTime並將日期加一天吧

@model DateTime
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h1>Home</h1>

    <ul>
        <li>date1: @ViewData["date1"]</li>
        <li>date2: @ViewBag.date2</li>
        <li>date1: @(((DateTime)ViewData["date1"]).AddDays(1))</li> //必須告知為DataTime才可以使用AddDays
        <li>date2: @ViewBag.date2.AddDays(1)</li> //Dynamic type不用告知DataTime即可使用AddDays
        <li>Model: @Model.AddDays(1)</li>
    </ul>
</body>
</html>

參考
參考文件
MVC美學


上一篇
[2020鐵人賽] Day9 - 控制器(Controller)
下一篇
[2020鐵人賽] Day11 - KendoUI & jQuery引用
系列文
打net core肉飯30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言