`
380071587
  • 浏览: 447784 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Razor表达式

 
阅读更多

Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace _04_RazorExpression.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }
}
View:

@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<div>
    <h1>
        1.基本字符串数组操作</h1>
    @{var items = new string[] { "one", "two", "three" };}
    <ul>
        @{foreach (string item in items)
          {
            <li>The item name is : @item</li>
          }
        }
    </ul>
    Items total:@items.Length;
    <h1>
        2.显式代码(括号)表达式:@@()</h1>
    @{string myApp = "Model";}
    <span>@(myApp).Models</span>
    <h1>
        3.@@转义符号:@@@@</h1>
    <span>zhangqs008@@163.com</span>
    <h1>
        4.Html编码输出:Html.Raw()</h1>
    @{string message = "<script type='text/javascript'>alert('Hello!');</script>";
      string message2 = "<b>alert('Hello!');</b>";
    }
    <span>@message</span> <span>@Html.Raw(@message2)</span>
    <h1>
        5.javascript中的编码:Ajax.JavaScriptStringEncode()</h1>
    <script type="text/javascript">
        $(function () {
            var message = "Hello @ViewBag.Message";
            $("#output").html(message).show();

            //当在Javascript中将用户提供的值赋给变量时,要使用javascript字符串编码,而不仅仅是Html编码,记住这一点很重要。
            var message2 = "Hello @Ajax.JavaScriptStringEncode(@ViewBag.Message)";
            $("#output2").html(message2).show();
        });</script>
    <span id="output"></span>
    <br />
    <span id="output2"></span>
    <h1>
        6.混合代码和纯文本:@@:</h1>
    @{ bool showMessage = true;
       if (showMessage)
       {
        @:this is plain text
       }
    }
    <h1>
        7.代码注释 @@*...*@@</h1>
    @*{
    bool showMessage = true;
       if (showMessage)
       {
        @:this is plain text
       }}
    *@
</div>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
        http://asp.net/mvc</a>.
</p>
效果图:


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics