MVC3学习总结

本文是阅读了ScottGu's blog来记录的,外加自己的学习心得。

原文地址:http://weblogs.asp.net/scottgu/archive/2011/01/13/announcing-release-of-asp-net-mvc-3-iis-express-sql-ce-4-web-farm-framework-orchard-webmatrix.aspx#7692548。方便以后查阅。

一:Razor

Razor是一个新的视图引擎,它实现了快速,流畅的编码流程,使得视图模板跟简洁干净。

1:灵活的选择。

  Add->View... 新建视图模板的时候你可以选择Razor(cshtml)模板视图,或aspx(c#)模板视图。

2:Razor和aspx语法的比较  

  变量variable:

    在.aspx中的Hello:<%= name %> 在Razor中不需要显示的闭合代码块Hello:@name

  循环及嵌套:

    <ul><%foreach(var p in Model){%>

    <li><%=p.Id%></li>

    <%}%> </ul>

    而在Razor引擎中:

    <ul>@foreach(var p in Model){

    <li>@p.Id</li>

    }<ul>

  if语句代码段:

  @if(条件){//...}else{//...}

  如果要输出@,则用@@就可以输出一个@。

    eg:<p>what's you time? it's @@DateTime.Now</p>    页面输出what's you time? it's @DateTime.Now

 Razor中支持aspx引擎中的Html Helper.  使用方式:@Html.TextBoxFor(m=>m.name)

3:自定义可以重复使用的Html helper:

    @helper themelist(int i)

    {

      if(i==0)

      //do sth..;

      else //do 2;

    }

  调用时直接@themelist(3)

3 :@model

  动态类型不需要使用inherite system.web.mvc.Iviewpag<..>   直接使用@model 强类型  eg: @model Mvc3UrlPro.Models.urlclass

4: _layout.cshtml与_viewstart.cshtml页面载入

    _viewstart.cshtml页:首次运行预先加载项,它作用为页面指定模板页。只需要在View文件夹内加入_ViewStart页面,就无需在每个具体的页面引入模板页。

    _layout.cshtml页:实现框架的页面,即模板页。

    每次打开一个页面时,先进_ViewStart页面,根据页面内指定的模板页再运行该指定名称的模板页,默认模板页名称为:_Layout.cshtml。

5:Razor中在服务端的注释使用 @* 注释语句*@

6:Razor中的@:和<text>使用

    @: :显式的指定一行代码块  eg:  @if(DateTime.Now.Year == 2011) {

                        @:this year is 2011<br />the date:@DateTime.Now

                        }

    显示多行代码块可以使用多个@:  eg  @:this year is 2011;

                     @:and it's a happy time;

    或者使用Razor中的<text></text>标识来显示多行代码块    <text>

                                   if(a==b)

                                  {显示正确;}

                                  else 显示错误;

                              </text>

7:代码表达式@ 及@()

    由于Razor解析算法的方式。需要 @()  显式代码

    eg:      @( A.Sum() / B.Count() )      <Img src="/Images/@( p.photo.name).jpg"/>

8:Razor中的_Layout模板页和Section

  _Layout模板页中的@RenderBody():  呈现页面主体   载入页面的body内容

    @RenderSection("Sectionname",required:true/false) : 预定义模板中的段 在页面载入时载入定义好的段节

    eg @section Sectionname{

    <p>this is a section one</p>

    //content....

    }    具体的section定义是定义在页面中。

原文地址:https://www.cnblogs.com/Joans/p/1952518.html