如果想展示HTML標記,則需返回System.Web.IHtmlString對象的實例,Razor不對它進行編碼,也可用Html.Row來顯示
@{
String message=“<scritp>alert('Olive')</script>”;}
<span>@Html.Row(message)</span>
這樣就可以顯示彈框了
與此同時,在Javascript中將用戶提供的值賦給變量時,要使用Javascript字符串編碼而不是HTML編碼,也就是用
@Ajax.JavaScriptStringEncode方法來對用戶的輸入進行編碼的
這樣就可以有效的避免跨站腳本的攻擊,如下:
<script type=“text/javascript”>
$(function(){
Var message='Hello @Ajax.JavaScriptStringEncode(ViewBag.UserName)';
$(“#message”).html(message).show('slow');
});
</script>
Razor語法示例
1、隱式代碼表達式
<sapn>@model.Message</span>
Razor中隱式表達式總是採用HTML編碼方式
2、顯示代碼表達式
<span>ISBN@(isbn)</span>
3、無編碼代碼表達式
使用Html.Row方法來確定內容不被編碼
<span>@Html.Row(model.Message)</span>
4、代碼塊
@{
Int x=123;
String y=“because”;
}
5、文本和標記組合
@foreach(var item in items)
{ <span>Item @item.Name.</span>}
6、混合代碼和純文本
@if(show)
{
<text>This is Olive</text>
}
或者
@if(show)
{
@This is Olive
}
佈局
ASP.NET MVC 3中的佈局相當於WebForm中的母版頁
如下佈局頁中部分代碼:
<div id=“main-content”>@RenderBody()</div>
其中的@RenderBody()相當於WebFrom中的placeholder佔位符
佈局使用示例:
@{
Layout=“~</Views/Shared/Layout.cshtml”;
}
<span>This is main content!</span>
此外,佈局中還可能有多個節,如下:部分佈局頁代碼示:
<div id=“main-conten”>@RenderBoday()</div>
<footer>@RenderSeciton(“Footer”)</footer>
如果對視圖頁不做任何改變則會報錯,這裏需要對視圖頁做如下修改
@{
Layout=“~</Views/Shared/Layout.cshtml”;
}
<p>This is a main content!</p>
@section Footer{
This is the <strong>footer</strong>
}
@section語法爲佈局中定義的一個節指定了內容,在默認的情況下視圖必須爲佈局中定義的節指定內容,但是
RenderSection方法有一個重載 版本,允許指定不需要的節,即爲required參數傳遞一個false值來標記Footer節是可選的,如下:
<footer>@RenderSection(“Footer”,false)</footer>
也可以定義一些薯條中沒有定義節時的默認內容,方法如下:
<footer>
@if(IsSectionDefined(“Footer”))
{
RenderSection(“Footer”);
}
Else
{
<span>This is the default footer.</span>
}
</footer>