如果想展示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>