ASP.NET MVC 3.0 新特性之View

ASP.NET MVC 3.0 新特性之View

asp.net mvc 之 asp.net mvc 3.0 新特性之 View(Razor):

  • Razor 的语法
  • Razor 与 Model
  • Razor 与布局



示例
1、Razor 概述
RazorDemoController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
using MVC30.Models;
 
namespace MVC30.Controllers
{
    public class RazorDemoController : Controller
    {
        public ActionResult Summary()
        {
            return View();
        }
    }
}


Summary.cshtml

@{
    ViewBag.Title = "Razor 概述";
}
 
<p>
使用 Razor 之前,要在 Web.Config 中做如下配置
<br />
<textarea rows="20" style="width: 100%">
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>
 
  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
</textarea>
</p>
 
<p>
    View 在每次 Render 之前都会先执行 _ViewStart.cshtml 中的代码
</p>



2、Razor 语法简介
RazorDemoController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
using MVC30.Models;
 
namespace MVC30.Controllers
{
    public class RazorDemoController : Controller
    {
        public ActionResult Syntax()
        {
            return View();
        }
    }
}

 
Syntax.cshtml

@{
    ViewBag.Title = "Razor 语法";
}
 
<p>
    使用@符号加{},直接在 html 页面中写 C#
    <br />
    @{ var currentTime = DateTime.Now; } @* 相当于 <% Htmlvar currentTime = DateTime.Now; %> *@
    @currentTime.ToString("yyyy-MM-dd")
</p>
 
<p>
    使用@符号,直接在 html 页面中写 C# 并输出结果
    <br />
    当前 URL:
    @Request.Url @* 相当于 <%= Request.Url %> *@
    <br />
    当前 URL:
    @{
        @Request.Url;
    }
</p>
 
<p>
    想输出字符@怎么办?,那就@@
    <br />
    webabcd@@abc.com
</p>
 
<p>
    在 Razor 中写服务端注释(客户端不可见)
    @* code *@
</p>
 
<p>
    Razor 自带的类型转换方法
    <br />
    例:AsInt(), IsInt(), AsBool(), IsBool(), AsFloat(), IsFloat(), AsDecimal(), IsDecimal(), AsDateTime(), IsDateTime()
    <br />
    类似 AsInt() 的方法会有一个重载方法 AsInt(int defaultValue),用于当转换失败时返回指定的默认值
    @{
        var tmp = "2/14/1980";
        var date = tmp.AsDateTime();
    }
    @date.ToString("yyyy-MM-dd")
</p>
 
<p>
    输出文本的方法
    <br />
    @*
        <text></text>
        或者
        @:
    *@
    @{
        <text>我是文本</text>
        <br />
        @:我是文本
    }
</p>
 
<p>
    获取文件的 URL 绝对路径的方法,一般用于 img 标签,link 标签,a 标签中所引用的文件的完全 url 路径
    <br />
    <img alt="" src="@Href("~/Content/themes/base/images/ui-icons_888888_256x240.png")" />
</p>
 
<p>
    Html Helper, Ajax Helper, Url Helper 依然可以使用
    <br />
    @Html.TextBox("txt", "我是 TextBox")
</p>

 

3、Razor 的与 Model 相关的 Demo
User.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace MVC30.Models
{
    public class User
    {
        public int ID { get; set; }
         
        public string Name { get; set; }
 
        public string Password { get; set; }
 
        public string ConfirmPassword { get; set; }
 
        public DateTime DateOfBirth { get; set; }
 
        public string Comment { get; set; }
    }
}


RazorDemoController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
using MVC30.Models;
 
namespace MVC30.Controllers
{
    public class RazorDemoController : Controller
    {
        // 用于演示 View 如何获取数据
        public ActionResult Model()
        {
            // ViewBag 的本质就是把 ViewData 包装成为 dynamic 类型
            ViewBag.Author = "webabcd";
 
            var list = new List<User>()
            {
                new User { ID = 1, Name = "webabcd", DateOfBirth = new DateTime(1980, 2, 14), Comment = "<b>mvp</b>" },
                new User { ID = 2, Name = "prettygyy", DateOfBirth = new DateTime(1981, 6, 26), Comment = "<b>mvp</b>" }
            };
 
            return View(list);
        }
    }
}


_MyLayout_ParitalView.cshtml

@*
    通过 @model 指定 Model 的类型,同时 Model 对象就是 Html.Partial() 或 Html.RenderPartial() 时传递过来的对象
*@
 
@using MVC30.Models;
@model User
            
<li>@Model.Name</li>


Model.cshtml

@*
    通过 @using 引入命名空间
    通过 @model 指定 Model 的类型,同时 Model 对象就是 Action 返回的数据
*@
 
@using MVC30.Models;
@model List<User>
 
@{
    ViewBag.Title = "Razor 的与 Model 相关的 Demo";
}
 
<p>
    <!--
        演示 ViewBag 的用法
    -->
    Author: @ViewBag.Author
</p>
 
<div>
    <ul>
        <!--
            Model 就是 Action 返回的数据
        -->
        @foreach (var user in Model)
        {
            if (@user.Name == "webabcd")
            {
                <!--
                    默认输出的是经过 HTML 编码后的数据,如果需要输出原始数据则使用 Html.Raw()
                -->
                <li>@user.Name (@Html.Raw(@user.Comment))</li>
            }
            else
            {
                <li>@user.Name (@user.Comment)</li>
            }
        }
    </ul>
</div>
 
 
<!--
    Html.Partial 与 Html.RenderPartial 的区别:
        Html.Partial - 直接将 View 的结果作为一个字符串输出
        Html.RenderPartial - 将 View 作为一个用户控件嵌入到当前的 HttpContext 中
 
    Html.Action 与 Html.RenderAction 的区别(演示参见 ControllerDemo/ChildActionOnlyDemo.cshtml):
        Html.Action - 直接将 Action 的结果作为一个字符串输出
        Html.RenderAction - 将 Action 作为一个用户控件嵌入到当前的 HttpContext 中
 
    Html.Partial, Html.RenderPartial 与 Html.Action, Html.RenderAction 的区别:
        二者都需要指定 View,前者的 View 不需要 Action,而后者的 View 必须要有 Action
-->
<div>
    <ul>
        @foreach (var user in Model)
        {
            @Html.Partial("_MyLayout_ParitalView", user)
            @*
                <%= Html.Partial("_MyLayout_ParitalView", user) %>
            *@
        }
    </ul>
</div>
 
<div>
    <ul>
        @{
            var firstUser = Model.First();
            Html.RenderPartial("_MyLayout_ParitalView", firstUser);
            @*
                <% Html.RenderPartial("_MyLayout_ParitalView", firstUser); %>
            *@
        }
    </ul>
</div>



4、Razor 的与布局相关的 Demo
RazorDemoController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
using MVC30.Models;
 
namespace MVC30.Controllers
{
    public class RazorDemoController : Controller
    {
        public ActionResult LayoutView()
        {
            return View();
        }
    }
}


_ViewStart.cshtml

@{
    // View 在每次 Render 之前都会先执行 _ViewStart.cshtml 中的代码
    Layout = "~/Views/Shared/_Layout.cshtml";
}


_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <!--
        Url.Content() - 将指定的相对路径转换为绝对路径
    -->
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
 
<body>
    @RenderBody()
</body>
</html>


_MyLayout_MasterPage.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    <div style="background-color: Gray">
        <!--
            引用此 Layout 的页上的未指明 Section 的内容会在此 Render
        -->
        @RenderBody()
    </div>
    @if (IsSectionDefined("mySection"))
    {
        // 引用此 Layout 的页后,如果指定名为 mySection 的 Section 的话,其会在此处 Render
        // 第二个参数的意思是,引用此 Layout 的页是否必须有名为 mySection 的 Section
        @RenderSection("mySection", false)
    }
    else
    {
        @:没有 mySection
    }
</body>
</html>


_MyLayout_RenderPage.cshtml

<h1>
    RenderPage
    <br />
    @{
        // 获取 RenderPage() 传递过来的参数
        if (@PageData["param"] == "abc")
        {
            @:param == "abc"
        }
        if (@PageData["param2"] == "xyz")
        {
            @:param == "xyz"
        }
    }
</h1>


LayoutView.cshtml

@{
    // 指定一个 Layout 页(相当于母版页)
    Layout = "_MyLayout_MasterPage.cshtml";
    ViewBag.Title = "Razor 的与布局相关的 Demo";
}
 
<!--
    在 Layout 中的 RenderBody() 中显示
    RenderPage() 的第二个参数的意思:给 _MyLayout_RenderPage.cshtml 传递参数
-->
在 RenderBody() 中显示的内容
@RenderPage("~/Views/RazorDemo/_MyLayout_RenderPage.cshtml", new { param = "abc", param2 = "xyz"})
 
<!--
    在 Layout 中的 RenderSection("mySection") 中显示
-->
@section mySection {
    <b>My Section</b>
}



5、其他

<p>
    Razor 的 dll 在这里 C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies
</p>
<p>
    Razor 中约定:布局 View 或者需要被别的 View 引用的 View 要以“_”开头
</p>
<p>
    asp.net mvc 3.0 的 T4 模板的位置在 D:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 3\CodeTemplates
    <br />
    如果不想修改默认模板的话,那么就将模板安装到当前项目中,然后只修改当前项目的 T4 模板,方法如下:
    <br />
    Tools -> Library Package Manager -> Package Manager Console,然后输入 install-package mvc3codetemplatescsharp,之后 CodeTemplates 文件夹就会添加到当前项目中
</p>
<p>
    新增的 HTML Helper,例如:Chart, WebGrid, WebImage, WebMail, Crypto 等,详见 System.Web.Helpers.dll

</p>

posted @ 2011-07-27 20:25  mrgao  阅读(602)  评论(1编辑  收藏  举报