"Reprint" "MVC Learning Razor Grammar"

Source: Internet
Author: User
Tags new set

Razor is the new view engine in MVC3. We know that in ASP. aspx, the view engine relies on <% and%> to invoke C # directives. MVC3 later has a new set of razor syntax that uses the @ tag, which is more flexible and concise. Here are some simple examples to get everyone to quickly hold on to the use of razor syntax.

Preparatory work

Before we demonstrate the use of the razor syntax, we need to do some preparatory work.

1. Opening vs Creating an ASP. Empty project is simply not a concrete demonstration.

2. Add a model. Add a class named Product in the models folder of your project. Here we use the product class of the previous C # Knowledge point feed to move it around. 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;}}    }

3. Add a controller. Right-click the Controllers folder in the project and select Add controller, named as shown:

After the point is added, the code in Prodcutcontroller is edited 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 = "Apple",                Description = "Big Red apple",                Category = "fruit", price                = 5.9M            };            Return View (MyProduct);}}    

4. Add a view. Right-click the index method and select Add view to configure the popup window as follows:

Click Add, the system automatically help us create a product folder and a index.cshtml file, index.cshtml content as follows:

@model mvcapplication1.models.product@{    viewbag.title = "Index";} 

5. Modify the default route. For convenience, we should let the application start directly to the request processing we need (here is Product/index). Open the Global.asax file, locate the Routes.maproute method under the Register route RegisterRoutes method, and change the controller value to "Product" as follows:

Routes. MapRoute (    "Default",//route name    "{controller}/{action}/{id}",//URL with parameter    new {controller = "Product", action = "Index", id = urlparameter.optional}//parameter default value);

Regardless of what these mean, I'll cover routing in a later article. To this, we can press F5, the program can run normally, ready to work is done.

Using the Model object

Introducing the razor syntax, let's start with the first line of the index.cshtml file:

@model MvcApplication1.Models.Product

Razor statements begin with the @ sign. Each view has its own model property (called by @model). The above code means to point the type of the model property of this view to the MvcApplication1.Models.Product type, which implements a strong type. One of the benefits of a strong type is type safety, and if a member name of the model object is written incorrectly, the compiler will error, and another benefit is that you can use the Code intelligence hints in VS to automate code writing for type member invocation. Of course, this code does not work properly, just to write code caused some difficulties.

The Model property in the view is used to hold the model instance object passed by the controller (in this example, Productcontroller through return view (MYPRODUCT) to the index view). The following code shows how to invoke the Model object:

@model mvcapplication1.models.product@{    viewbag.title = "Index";} <!--Call the product instance's Name property-->

Note that the first line of code is used for the Fame model property type with the @model <model type name >(lowercase m), and the model object passed by the calling controller is @model. < properties name > (capital M). Press F5 to run the effect as follows:

Using an expression

The use of the model object described above is a very common type of razor code. In fact, the @model.name in the example above is a simple expression that represents the text value that renders model.name to a Web page. Expressions in the Razor syntax can use either the model object or almost any other object within the scope of an accessible permission to output the text value of the object's members to the web. As shown in the following code:

@model mvcapplication1.models.product@{    viewbag.title = "Index";} The time now is: @DateTime. now.toshorttimestring ()

The results are as follows:

This simple expression that uses the object (@DateTime. now.toshorttimestring () and @model.name), which we do not call an object expression.

In addition to an object expression, it can be any other expression that has a return value, such as a conditional expression. As shown in the following code:

@model mvcapplication1.models.product@{    viewbag.title = "Index";} The time now is: @DateTime. now.toshorttimestring () <br/>@ (datetime.now.hour>22? "Early, write a few more!" ":" It's time to go to bed! ")

The results are as follows:

Note that it is generally necessary to enclose a non-object expression in parentheses.

Using code blocks

As with expressions, you can use a single C # procedure control block (such as if, switch, for, and so on) that is enclosed in {} in the Razor syntax. Use the following methods:

@model mvcapplication1.models.product@{    viewbag.title = "Index";} @if (Model.price > 5M) {    string test = "Cannot afford!" ";    <p> @Model. Name <b> too expensive! </b> @test </p>}

The effect is as follows:

Any C # code can be written within a block of code enclosed by {}, or any HTML tag can be used. However, it is important to note that when there is only one line of code inside a control statement, you cannot omit the curly braces as you would write C # background code.

There is also a more common way to use code blocks. You can also use blocks of code by starting with @{and closing the block, which can put multiple blocks of code together and open them into a larger block of code. As shown in the following code:

@model mvcapplication1.models.product@{    viewbag.title = "Index";} @{    if (model.category== "fruit") {        string test= "is a kind of fruit. ";        @Model. Name @test    }    if (Model.price > 5M) {        string test = "Cannot afford!" ";        <p> @Model. Name <b> too expensive! </b> @test </p>    }}

The results of the operation are as follows:

Use @: and text tags

We note that in code blocks, either C # code, or HTML tags, cannot write plain text directly, and plain text should be wrapped in HTML tags. However, if you need to output plain text in a code block without HTML tags, you can use the @: tag, which is useful for outputting plain text text in a block of code. As shown in the following code:

... @if (Model.price > 5M) {    @[email protected]: too expensive.    <br/>    @: @@: The following can be any text except the @ character, including <, > and spaces, how to write the output.    <br/>    @: If you want to output the @ symbol, you can use the @ symbol when there are non-sensitive characters before and after the @ symbol (such as <, {, and spaces), otherwise you need to use the two @ symbol. }

Note the use of the @ symbol. The above code works as follows:

It is convenient to use the @: tag to output a line of text without HTML tags in a code block, but if you need to output continuous or discontinuous multiline plain text in a code block, it is convenient to use the text label, as shown in the following code:

... @if (Model.price > 5M) {    <text>    name:<b> @Model. name</b><br/>    Category: <b>@ model.description</b><br/>    Price:<b> @Model. price</b><br/>        <pre>        Test line one: <a>aaaa</a>        Test Line II: @@ [email protected]    </pre>    </text>}

Operation Result:

Using ViewBag

It says that passing data from a controller to a view is done through the model object. Like the model object, the ViewBag object can also be used to pass data from the controller to the view. The following code shows how to use ViewBag in Productcontroller:

Public ActionResult Index () {    Product myproduct = new Product {        ProductID = 1,        Name = "Apple",        Description = " Big Red apple "        Category =" fruit ", price        = 5.9M    };    Viewbag.teststring = "This is a line of test text!" ";    Return View (myproduct); }

Not the same, ViewBag is a dynamic type, where teststring is defined by itself. ViewBag is used in view in the same way as model, as follows:

... The time for dynamic expression parsing is: @ViewBag. teststring

The result of the operation is not mapped.

Using Layuot

Before we created a view, we checked the use of the layout and master page, but didn't tell vs which one to use. Please look carefully:

This dialog box tells us to "leave blank if this option is set in Razor _viewstart." In the Views folder of the project, we can see a _viewstart.cshtml file that contains:

@{    Layout = "~/views/shared/_layout.cshtml";}

When MVC renders a view, the _viewstart.cshtml file is automatically found by default as the master to render the view requested by the user. The rendering of the master is handled internally by MVC, and this view file, which begins with an underscore (_), is generally not directly returned to the user.

The advantage of using a layout or master page is that we don't need to set up a single copy of the same content in each view. According to the path indicated by the contents of the _viewstart.cshtml file, we find the _layout.cshtml file, open it will find that we defined in the Index view of Viewbag.title = "Index" is called here:

<! DOCTYPE html>

Similar to the ContentPlaceHolder server control in an ASP. NET master page, using @renderbody () in MVC renders the content of a child Web page, which saves us from writing the same HTML elements, JS, and styles in each view file.

If you create a view and don't want to use layout, you can cancel the use Layout and master Page option in the dialog box that creates the view, and the following code is generated when you create it:

@{    Layout = null;} <! DOCTYPE html>

Because layout is not used, the view must contain every basic element used to render the HTML page, and Layout=null must be specified.

Reference:
Pro ASP. NET MVC 3 Framework

"Reprint" "MVC Learning Razor Grammar"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.