Home > Backend Development > C#.Net Tutorial > [ASP.NET MVC Mavericks Road] 03 - Razor syntax

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

黄舟
Release: 2016-12-30 13:55:54
Original
1099 people have browsed it

[ASP.NET
MVC Mavericks Road]03 - Razor syntax

Razor is a new view engine only in MVC3. We know that in ASP.NET, the ASPX view engine relies on to call C# instructions. After MVC3, there is a new set of Razor syntax using the @ mark, which is more flexible and concise to use. Here are some simple examples to help you quickly master the use of Razor syntax.

Contents of this article


Preparation work

Before demonstrating the use of Razor syntax, we need to do some preparation work.

1. Open VS and create an ASP.NET MVC empty project. It is very simple and will not be demonstrated in detail.

2. Add a Model. Add a class named Product in the Models folder of the project. Here we move over the Product class used in the previous C# knowledge point summary. The code is as follows:

namespace MvcApplication1.Models {
    public class Product {
        public int ProductID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public string Category { set; get; }
    }
}
Copy after login

3. Add a Controller. Right-click the Controllers folder in the project, select Add Controller, and name it as shown below:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

After clicking Add, edit the code in ProdcutController as follows:

using System.Web.Mvc;
using MvcApplication1.Models; 

namespace MvcApplication1.Controllers
{
    public class ProductController : Controller
    {
        public ActionResult Index()
        {
            Product myProduct = new Product {
                ProductID = 1,
                Name = "苹果",
                Description = "又大又红的苹果",
                Category = "水果",
                Price = 5.9M
            };
            return View(myProduct); 
        }
    }
}
Copy after login

4. Add a View. Right-click the Index method, select Add View, and configure the following in the pop-up window:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

After clicking Add, the system automatically creates a Product folder and an Index.cshtml for us. The content of the file, Index.cshtml, is as follows:

@model MvcApplication1.Models.Product

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
Copy after login

5. Modify the default route. For convenience, we should direct the application startup to the request processing we need (in this case Product/Index). Open the Global.asax file, find the routes.MapRoute method under the RegisterRoutes method, and change the value of controller to "Product", as shown below:

routes.MapRoute(
    "Default", // 路由名称
    "{controller}/{action}/{id}", // 带有参数的 URL
    new { controller = "Product", action = "Index", id = UrlParameter.Optional } // 参数默认值
);
Copy after login

Regardless of what these mean, I will explain it later. The article is dedicated to routing. At this point, we can press F5, the program can run normally, and the preparations are done.

Using Model Object

Introducing Razor syntax, let us start from the first line of the Index.cshtml file:

@model MvcApplication1.Models.Product
Copy after login

Razor statements all start with the @ symbol. Each view has its own Model property (called via @Model). The above code means to point the type of the Model attribute of this view to the MvcApplication1.Models.Product type, which implements strong typing. One of the benefits of strong typing is type safety. If you write a wrong member name of the Model object, the compiler will report an error; another benefit is that you can use the code intelligent prompts in VS to automatically complete the code writing of type member calls. . Of course, this code can run normally without a program, but it just creates certain difficulties in writing code.

The Model property in the view is used to store the model instance object passed by the controller (In this example, ProductController is passed to the Index view through "return View(myProduct)"), the following code Demonstrates how to call the model object:

@model MvcApplication1.Models.Product

@{
    ViewBag.Title = "Index";
}
<!-- 调用Product实例的Name属性 -->
<h2>名称:@Model.Name</h2>
Copy after login

Note that the first line of code used to declare the Model attribute type uses @model (lowercase m), and the Model object passed by the calling controller uses @Model. (capital M). Press F5 to run as follows:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

Use expression

上面讲的使用Model对象是很常用的一种Razor代码。其实上面示例中的@Model.Name就是一个简单的表达式,表示向Web页面呈现Model.Name的文本值。Razor语法中的表达式除了可以使用Model对象,也可以使用几乎任何一个其他可访问权限范围内的对象,来向Web面面输出该对象成员的文本值。如下代码所示:

@model MvcApplication1.Models.Product

@{
    ViewBag.Title = "Index";
}

现在的时间是: @DateTime.Now.ToShortTimeString()
Copy after login

运行效果如下:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

这种使用对象的简单表达式(@DateTime.Now.ToShortTimeString()和@Model.Name),在这我们不防称之为对象表达式。

除了对象表达式,还可以是其他任意的有返回值的表达式,如条件表达式。如下面代码所示:

@model MvcApplication1.Models.Product

@{
    ViewBag.Title = "Index";
}

现在的时间是: @DateTime.Now.ToShortTimeString()


@(DateTime.Now.Hour>22 ? "还早,再写一会吧!" : "该睡觉咯!")
Copy after login

运行效果如下:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

注意,一般使用非对象表达式时都需要用小括号括起来。


使用代码块

和表达式的使用方式一样,Razor语法中也可以使用由{}括起来的单个C#过程控制代码块(如if、switch、for等)。使用方式如下:

@model MvcApplication1.Models.Product

@{
    ViewBag.Title = "Index";
}

@if (Model.Price > 5M) {
    string test = "买不起!";
    <p>@Model.Name <b>太贵了!</b> @test </p>
}
Copy after login

效果如下:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

由{}括起来的代码块内可以写任何C#代码,也可以使用任何HTML标签。但需注意的是,当控制语句内只有一句代码时不能像写C#后台代码一样省略大括号。

还有一种更常用的使用代码块的方式。你也可以通过以@{开始,以}闭合的方式来使用代码块,它可以把多个代码块放在一起,开成一个更大的代码块。如下代码所示:

@model MvcApplication1.Models.Product

@{
    ViewBag.Title = "Index";
}
@{
    if(Model.Category=="水果"){
        string test="是一种水果。";
        @Model.Name @test
    }
    if (Model.Price > 5M) {
        string test = "买不起!";
        <p>@Model.Name <b>太贵了!</b> @test </p>
    } 
}
Copy after login

运行结果如下:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

使用@:和text标签

我们注意到,在代码块中,要么是C#代码,要么是HTML标签,不能直接写纯文字,纯文字须包裹在HTML标签内。但如果需要在代码块中直接输出纯文字而不带HTML标签,则可以使用@:标签,在代码块中输出纯文本文字非常有用。如下代码所示:

...

@if (Model.Price > 5M) {
    @Model.Name@:太贵了 。
    <br />
    @: @@:后面可以是一行除@字符以外的任意文本,包括<、>和空格,怎么写的就怎么输出。
    <br />
    @: 如果要输出@符号,当@符号前后都有非敏感字符(如<、{、和空格等)时,可以直接使用@符号,否则需要使用两个@符号。
}
Copy after login

注意@符号的使用。上面代码运行效果如下:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

使用@:标签在代码块中输出一行不带html标签的文本非常方便,但如果需要在代码块中输出续或不连续的多行纯文本,则使用text标签较为方便,如下代码所示:

...

@if (Model.Price > 5M) {
    <text>

    名称:<b>@Model.Name</b><br />
    分类:<b>@Model.Description</b><br />
    价钱:<b>@Model.Price</b><br />
    
    <pre class="brush:php;toolbar:false">
        测试行一: <a>aaaa</a>
        测试行二: @@ fda@aaa
    
Copy after login
}

运行结果:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

使用ViewBag

上面讲了通过Model对象来从Controller传递数据到View。和Model对象一样,ViewBag对象也可以用来从Controller传递数据到View。下面代码演示了如何在ProductController中使用ViewBag:

public ActionResult Index()
{
    Product myProduct = new Product {
        ProductID = 1,
        Name = "苹果",
        Description = "又大又红的苹果",
        Category = "水果",
        Price = 5.9M
    };
    ViewBag.TestString = "这是一行测试文字!";
    return View(myProduct); 
}
Copy after login

不一样的是,ViewBag是动态类型,其中TestString是自己定义的。ViewBag在View中的使用方式是和Model一样,如下:

...

动态表达式解析的时间是:@ViewBag.TestString
Copy after login

运行结果就不贴图了。


使用Layuot

前面我们创建一个视图的时候,我们勾选了使用布局和母版页,但没有告诉VS使用哪一个。请仔细看下图:

[ASP.NET MVC Mavericks Road] 03 - Razor syntax

这个对话框告诉我们“如果在Razor _viewstart中设置了此选项,则留空”。在项目的Views文件夹中,我们可以看到一个_ViewStart.cshtml文件,里面的内容是:

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

MVC呈现视图的时候,默认情况下会自动查找_ViewStart.cshtml文件,以它作为母版来呈现用户请求的视图。母版的呈现是MVC内部处理的,这种以下划线(_)开头的视图文件,一般是不能直接返回给用户。

使用布局或母版页的好处是,我们不需要在每个视图中都设置一份相同的内容。按照_ViewStart.cshtml文件内容指示的路径,我们找到_Layout.cshtml文件,打开它会发现我们在Index视图中定义的 ViewBag.Title = "Index" 就是在这里调用的:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>

<body>
    @RenderBody()
</body>
</html>
Copy after login

类似于ASP.NET母版页中的ContentPlaceHolder服务器控件,在MVC中使用@RenderBody()来呈现子Web页面的内容,它可以省去我们在每个视图文件中写相同的html元素、JS和样式等的工作。

如果创建一个视图不想使用Layout,则可以在创建视图的对话框取消“使用布局和母版页”选项,创建后会生成如下代码:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>About</title>
</head>
<body>
    <div>
        
    </div>
</body>
</html>
Copy after login

由于没有使用Layout,视图中必须包含用于呈现HTML页面每个基本元素,而且必须指定Layout=null。


 以上就是[ASP.NET MVC 小牛之路]03 - Razor语法的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template