mvc3 razor语法学习

1.多行声明:

@{

//cs代码

}

@{
int a=1;
string name="username:"+usename;
}

 

 

2.一行多变量声明

@(//cs代码)

<p>你最爱的:@("水果"+fruit)</p>

 

3.在多行代码块中,用<text>标签,显示的时候可以不显示任何标签

 

@if(true)
{
<text>
hello 

today 
is @Datetime.Now
</tex>

}

运行后的结果是:

hello 

today is 2011 7 1

 

标签没有了.

 

 

4@:

@:提示模板引擎这一行为内容块输出,不用解释

 

 

 

 

5.页面布局 section

/// <param name="section">sectionname</param>
/// <param name="required">子页面是否要重写这个section,默认是true</param>

@RenderSection(
"sectionname",required:false)

 如果required:true   则子页面一定要实现这个section,不然会出现运行时错误

 

还可以定义默认的局部布局内容,eg:

@if(IsSectionDefined("sectionname")){

  @RenderSection(
"sectionname")    

}
else{

     
//为默认内容

}

 

实现在母版页使用的section

@section SideBar{
  
//自定义section内容

}

 

_ViewStart.cshtml   为所有页面引用了通用模板页,在其它子页面不用再次引入

_ViewStart.cshtml  里面的内容

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

在其它页面就可以不用写了

 

默认所有的页面都使用了通用的模板,如果某个页面不想使用通用模板,则应该加上这个:

 

@{
    Layout = "";
}

这样就可以摆脱通用模板的干扰了

 

 

 6  @*    *@  为注释

 

 

@{string a="<a>111</a>";}

想要输出html,可以三种方式:
@Html.Raw(a)
@MvcHtmlString.Create(a)
@{WriteLiteral(a);}

 

@(new HtmlString( "<h1>asdfasd</h1>")) 
@(Html.Encode("<h1>asdfasd</h1>"))


7 helper

在项目下新建app_code文件夹,在app_code中新建一个视图文件Content.cshtml,删除里面的Code,并将原Layout.cshtml中的helper部分copy
到Content.cshtml下,这是发现Url缺少引用声明。添加@using System.Web.Mvc ,并添加一个的helper参数
 
@helper Script(string scriptName,UrlHelper Url)    

 可以这样调用了:

 @Content.Script("jquery-1.5.1.min.js", Url)

 

 

 

posted on 2011-07-01 15:51  viste_happy  阅读(612)  评论(0编辑  收藏  举报