zoukankan      html  css  js  c++  java
  • asp.net MVC Razor 语法(3)

    编程逻辑:执行基于条件的代码。

    If 条件

    C# 允许您执行基于条件的代码。

    如需测试某个条件,您可以使用 if 语句。if 语句会基于您的测试来返回 true 或 false:

    • if 语句启动代码块
    • 条件位于括号中
    • 如果条件为真,则执行花括号中的代码
      @{var price=50;}
      <html>
      <body>
      @if (price>30)
          {
          <p>The price is too high.</p>
          }
      </body>
      </html>
      

      Else 条件

      if 语句能够包含 else 条件

      else 条件定义条件为 false 时执行的代码。

    • @{var price=20;}
      <html>
      <body>
      @if (price>30)
        {
        <p>The price is too high.</p>
        }
      else
        {
        <p>The price is OK.</p>
        } 
      </body>
      </html>
      

      注释:在上面的例子中,如果价格不大于 30,则执行其余的语句。

      Else If 条件

      可通过 else if 条件来测试多个条件:

      @{var price=25;}
      <html>
      <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>
      </html>
      

      在上面的例子中,如果第一个条件为 true,则执行第一个代码块。

      否则,如果下一个条件为 true,则执行第二个代码块。

      您能够设置任意数量的 else if 条件。

      如果 if 和 else if 条件均不为 true,则执行最后一个 else 代码块。

      Switch 条件

      switch 代码块可用于测试一系列具体的条件:

      @{
      var weekday=DateTime.Now.DayOfWeek;
      var day=weekday.ToString();
      var message="";
      }
      <html>
      <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;
      }
      <p>@message</p>
      </body>
      </html>
      

      测试值 (day) 位于括号中。每个具体的测试条件以 case 关键词开头,以冒号结尾,其后允许任意数量的代码行,以 break 语句结尾。如果测试值匹配 case 值,则执行代码行。

      switch 代码块可为其余的情况设置默认的 case (default:),允许在所有 case 均不为 true 时执行代码。

  • 相关阅读:
    【腾讯敏捷转型NO.1】敏捷是什么鬼?
    【敏捷实用工具】JIRA介绍以及使用方法
    SpringCloud学习总结(三)——案例环境搭建
    SpringCloud学习总结(二)——SpringCloud微服务概述
    SpringCloud学习总结(一)——微服务基础知识
    IDEA jrebel 破解
    IDEA的几个常用配置,日常开发必备。
    java中实体类的区别
    zookeeper 学习总结(四)——基本使用
    zookeeper 学习总结(三)——linux上部署单机以及集群
  • 原文地址:https://www.cnblogs.com/liuruitao/p/3966775.html
Copyright © 2011-2022 走看看