ASP.NET Razor 簡介


目錄###

1. 什么是Razor
2. Razor C# 基本語法規(guī)則
3. 邏輯條件與循環(huán)
4. ASP.NET MVC 中 Razor 布局


razor

1. 什么是Razor ?

  • Razor 不是一種編程語言,而是一種標(biāo)記語法,可以將基于服務(wù)器的代碼(Visual Basic 和 C#)嵌入到網(wǎng)頁中。
  • Razor 是基于 ASP.NET 的,是為創(chuàng)建 Web 應(yīng)用程序而設(shè)計(jì)的。
  • Razor支持代碼混寫。
  • 帶 Razor 語法的 ASP.NET 網(wǎng)頁有特殊的文件擴(kuò)展名cshtml(Razor C#)或者vbhtml(Razor VB)。

2. Razor C#基本語法規(guī)則

① 使用@將代碼塊添加到頁面中
  • 內(nèi)聯(lián)表達(dá)式(Inline expressions)
  • 單語句塊(Single statement blocks)
  • 多語句塊(Multi-statement block)
<!-- Inline expressions -->
<p>You are using @Request.Broswer.Broswer!</p>

<!-- Single statement blocks  -->
@{ ViewBag.title = "Home Page"; }
@{ var myMessage = "Hello World"; }

<!-- Multi-statement block -->
@{
    var name = "Jason";
    var greeting = "Nice to meet you, ";
    var greetingMessage = greeting + name;
}
<p>The greeting is: @greetingMessage</p>
② 代碼塊括在大括號中,代碼語句用分號結(jié)束
③ 使用 var 關(guān)鍵字,聲明變量存儲(chǔ)值
<!-- Storing a string -->
@{ var welcomeMessage = "Welcome, new members!"; }
<p>@welcomeMessage</p>

<!-- Storing a date -->
@{ var year = DateTime.Now.Year; }
④ 字符串要用引號括起來
@{ var myString = "This is just an example"; }
⑤ C#代碼是區(qū)分大小寫
⑥ 空格和換行符不影響語句
  • 可以通過增加空格或者換行符提高代碼的可讀性。
  • 但是對于字符串,不可以
@{ var test = "This is a long
    string"; }  // Does not work!
⑦ 內(nèi)聯(lián)的helper方法
@helper formatAmount(decimal amount)
{
    var color = "green";
    if (amount < 0)
    {
        color = "red";
    }
    <span style="color:@color">@String.Format("{0:c}", amount)</span>
}

然后可以在其他地方使用helper方法,比如:

@{var amounts = new List<decimal> {100, 25.50m, -40, 276.99m}
}

<ul>
    @foreach(decimal amount in amounts)
    {
        <li>@formatAmount(amount)</li>
    }
</ul>
@{}中的內(nèi)容都會(huì)被視為C#代碼
  • 如果想要添加純文本,兩種方法
@ {
      //方法1
      <text>djskfadsfhadsjfk</text>
      //方法2
      @: fhdshfjskhfksfs
}
  • 輸出@符號
@ { <p>Have a good weekend @@LA</p> }
//output: Have a good weekend @LA
⑨ 注釋
  • 使用@**@
@*  A one-line code comment. *@
@*
    This is a multiline code comment.
    It can continue for any number of lines.
*@  
  • @{}中使用C#的注釋格式
@{
    // This is a comment.
    var myVar = 17;
    /* This is a multi-line comment
    that uses C# commenting syntax. */
}

3. 邏輯條件與循環(huán)

  • If-else, else if 語句
@ { var price = 25; }
<body>
@if (price >= 30)
{
    <p>The price is high.</p>
}
else if (price > 20 && price < 30) 
{
    <p>The price is OK.</p>
}
else
{
    <p>The price is low.</p>
} 
</body>
  • Switch 語句
@ { var day = "Monday"; }
<body>
@switch(day)
{
case "Monday":
    message="This is the first weekday.";
    break;
case "Thursday":
    message="Only one day before weekend.";
    break;
case "Friday":
    message="Tomorrow is weekend!";
    break;
default:
    message="Today is " + day;
    break;
}
  • For 循環(huán)
<!-- 方式1 -->
@for (int i = 0; i < 10; i++)
{
    @:@i
}
<!-- 方式2 -->
@{
    for (int i = 0; i < 10; i++)
    {
        //do something
    }
}
  • While 循環(huán)
<body>
@{
    var i = 0;
    while (i < 5)
    {
        i += 1;
        <p>Output is: @i</p>
   }
}
</body>
  • Foreach 循環(huán)
//定義一個(gè)數(shù)組
@{var amounts = new List<decimal> {100, 25.50m, -40, 276.99m}
}
//使用foreach遍歷數(shù)組
<ul>
    @foreach(decimal amount in amounts)
    {
        <li>@amount</li>
    }
</ul>

4. ASP.NET MVC 中Razor布局

Views folder
  • 在_ViewStart.cshtml中, 可以定義所有view的默認(rèn)layout模板
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
  • _Layout.cshtml即模板頁,起到頁面整體框架重用的目的
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title> 
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @Html.Partial("_header")
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        <div class="row">
            <div class="col-md-12">
                <img src="~/Content/Images/logo.png" class="img-responsive item-center"/>
            </div>
        </div>
        @RenderBody()
    </div>
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
    @Html.Partial("_footer")
</body>
</html>
  • @Html.Partial()
    HtmlHelper.Partial(),可以將頁頭、頁腳、登陸等局部視圖加載進(jìn)來
  • @RenderBody()
    將對應(yīng)View頁面的主內(nèi)容替換到此
  • @RenderSection()
    將對應(yīng)View頁面的相應(yīng)的section部分替換到此

相關(guān)資料

  1. Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)
  2. C# Razor Syntax Quick Reference
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容