964
技術社區[雲棲]
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 ></span>
<br />
<span ></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="https://asp.net/mvc" title="ASP.NET MVC Website">
https://asp.net/mvc</a>.
</p>
效果圖:

最後更新:2017-04-02 16:48:08