Chapter 2 - Working with Razor

A view engine processes the view content and insert dynamic content into the output sent to a browser, and razor is the name of the MVC Framework view engine.

1. Working with modal

@model PartyInvites.Models.Product

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Product</title>
</head>
<body>
    <div>
        @Model.Name
    </div>
</body>
</html>

Razor statements start with @ character. @model statement declares the type of the model object that I will pass to the view from the action method. This allows my to refer to the methods, fields, and properties of the view model object throught @Model.

2. Working with layout

@{layout = null;} is an example of a razor code block, which allows me to include C# statement in a view. The code block is opened with @{ and closed with }, the statements it contains are evaluated when the view is rendered.

The effect of setting layout to null is to tell the MVC framework that the view is self-contained.

Layouts are effectively templates that contain markup that you use to create consistency across your app - this could be to ensure that the right javascript libraries are included in the result or that a common look and feel is used throughout.

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Files in the views folder whose names begin with an underscore are not returned to the user. In the layout file, @Rendybody() method inserts the contents of the view specified by the action method into the layout markup. And the elements in the layout will be applied to any view that uses the layout and this is why layouts are essentially templates.

2.1 applying a layout

To apply the layout to the view, I just need to set the value of the Layout property.

@{
    ViewBag.Title = "Product1";
    Layout = "~/_BasicLayout.cshtml";
}

2.2 using a view start file

The process of setting layout in every view is error-prone process and difficult to maintain. This can be resolved by using a view start file. When it renders a view, the MVC framework will look for a file called ViewStart.cshtml. The content of this file will be treated as through they were contained in the view file itself and I can use this feature to automatically set a value for the layout property.

The content of _ViewStart.cshtml file.

@{
    Layout = "~/_BasicLayout.cshtml";
}

I do not have to specify that I want to use the view start file. The MVC framework will locate the file and use its contents automatically. The value defined in the view file take precedence, which makes it easy to override the view start file.

It is important to understand the difference between  setting layout to null and omitting layout statement.

3. Using Razor expression

Even though you can do quite a lot with Razor, including c# statement, but you should not use Razor to perform business logic or manipulate your domain model objects in any way.

And you should not format the data that your action method passed to the view. let the view engine figure out data it needs to display.

3.1 Inserting data values

The simplest thing you can do with Razor expression it to insert a data value into the markup. You can do this using the @Model expression to refer to the properties and methods defined by the view model. (@Model.Name, @Model.Price etc)

3.2 Settign attribute values

<div data-discount="@ViewBag.ApplyDiscount" data-express="@ViewBag.ExpressShip"></div>

3.3 Using conditional statements

Razor is able to process conditional statements, which means that I can tailor the output from a view based on values in the view data.

<table>
    <tr>
        <td>
            @switch ((int) ViewBag.ProductCount)
            {
                case 0:
                    @: out of stock
                    break;
                case 1:
                    <b>low stock</b>
                    break;
                default:
                    break;
            }
        </td>
    </tr>
</table>

To start a conditional statement, you place an @ character in front of the C# conditioanl keyword. The @: characters prevent Razor from interpreting this as a C# statement.

3.4 Enumerating arrays and collections

        public ActionResult Products()
        {
            Product[] array =
            {
                new Product(){ProductID = 1,Name="product1", Price = 20, Description = "des 1", Category = "cat1"},
                new Product(){ProductID = 2,Name="product2", Price = 21, Description = "des 2", Category = "cat2"},
                new Product(){ProductID = 3,Name="product3", Price = 22, Description = "des 3", Category = "cat3"},
            };
            return View(array);
        }
@using PartyInvites.Models
@model PartyInvites.Models.Product[]

@{
    ViewBag.Title = "Products";
    Layout = "~/_BasicLayout.cshtml";
}

@if (Model.Length > 0)
{
    <table>
        <thead><tr><th>Product</th><th>Price</th></tr></thead>
        <tbody>
            @foreach (Product p in Model)
            {
                <tr>
                    <td>@p.Name</td>
                    <td>@p.Price</td>
                </tr>
            }
        </tbody>
    </table>
}

3.5 Dealing with namespace

You can apply @using expression to bring a namespace into the context for a view, just like in a regular C# class.

@using Models

And you can apply multiple using statement.

时间: 2024-09-30 19:04:51

Chapter 2 - Working with Razor的相关文章

Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Validating User Inputs Using Filters Working with HTML and Tag Helpers Creating Data-Driven Web Applications Implementing Authentication and Authorization W

THE most basic way to implement ASP.NET Razor security

Wednesday, 9 February 2011   02:03 AM If you look at the ASP.NET Web Pages (aka Razor) tutorials on the ASP.NET web site, there's a chapter devoted to adding security to a site in the form of membership (that is, a login capability). This chapter bas

ANSI Common Lisp Chapter 2

Chapter 2 总结 (Summary) Lisp 是一种交互式语言.如果你在顶层输入一个表达式, Lisp 会显示它的值. Lisp 程序由表达式组成.表达式可以是原子,或一个由操作符跟着零个或多个实参的列表.前序表示法代表操作符可以有任意数量的实参. Common Lisp 函数调用的求值规则: 依序对实参从左至右求值,接着把它们的值传入由操作符表示的函数. quote 操作符有自己的求值规则,它完封不动地返回实参. 除了一般的数据类型, Lisp 还有符号跟列表.由于 Lisp 程序是

Json&amp;Razor&amp;控制器

JsonJson 属于JavaScript所以要书写在<script></script>中1.语法规则: 1.1:键值对 1.2:逗号分隔 1.3:花括号保存对象 1.4:方括号保存数组JSON的值可以为NULL2.JSON对象是在花括号内书写(键值对"{ "name":"小王" , "url":"www.xiaowang.com" }")3.使用数组的话则是用方括号包裹每个JSON

Razor:从aspx到cshtml常见错误及正确书写方法

http://blog.csdn.net/cheny_com/article/details/6298496 从aspx转到chshtml还是有很多要适应的地方的,本帖是个人学习笔记帖不断更新.每天开着本帖编程. 按第一个有意义的编译错误的首字母排序,便于查找: Cannot implicitly convert type 'void' to 'object' 错误:@Html.RenderPartial("_XXXX", Model); 正确:@{Html.RenderPartial

C# MVC分页,razor

IMVCPages interface IMVCPages { int GetItemsCount(); int GetPageSize(); int GetPagesCount(); /// <summary> /// 当前页面索引,用于分页 /// </summary> int CurrentPageIndex { get; set; } } View <div> 查询到 @Model.GetItemsCount() 条记录,共 @Model.GetPagesCou

Chapter 5 MySQL Server Administration_1

Chapter 5 MySQL Server Administration Table of Contents 5.1 The MySQL Server 5.1.1 Configuring the Server 5.1.2 Server Configuration Defaults 5.1.3 Server Option and Variable Reference 5.1.4 Server Command Options 5.1.5 Server System Variables 5.1.6

Notes : &lt;Hands-on ML with Sklearn &amp; TF&gt; Chapter 7

.caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px solid #000; } .table { border-collapse: collapse !important; } .table td, .table th { background-color: #fff !important; } .table-bordered th, .table-bordere

软工Chapter Six

软工Chapter six 团队和流程 典型的软件团队模式和开发流程是:主治医师模式.明星模式.社区模式.业余剧团模式.秘密团队.特工团队.交响乐团模式.爵士乐模式.功能团队模式:写了再改模式.瀑布模型.瀑布模型的各种变形.统一流程.老板驱动的流程.渐进交付的流程. 现在的编程离不开团队的合作,那么怎样的组合才能算是一个团队呢?首先,团队有一致的集体目标,团队要一起完成这目标.一个团队的成员不一定要同时工作,但一定要有共同的目标.另外团队成员有各自的分工,互相依赖合作,共同完成任务. 软件团队有