Study Note 7 of pro ASP. net mvc 3 framework [@ Syntax of mvc3 razor view engine]

Source: Internet
Author: User

Continue with the Notes for the second part mentioned last time: razor view Engine

1. What is razor:

Razor is a new view engine provided in mvc3. ASP. the net view engine looks for special elements that contain server commands to process web pages. As we noted earlier, the standard aspx view engine relies on <% and %> elements, this is very familiar to us. Through razor, the MVC development team introduced a new set of @-centered syntaxes. In general, as long as we are familiar with the <%> syntax, there will be no major problems with razor usage, although there may be some new rules.

2. Use of razor
Step 1: Create an empty mvc3 project razor and add a model for product. CS, as shown below:

namespace Razor.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 { get; set; }
}
}

Step 2: Add a controller as follows:

    public class ProductController : Controller
{

//GET: /Product/

public ActionResult Index()
{
Product myProduct = new Product
{
ProductID = 1,
Name = "Kayak",
Description = "A boat for one person",
Category = "Watersports",
Price = 275M
};

ViewBag.ProcessingTime = DateTime.Now.ToShortTimeString();
ViewData["ProcessingTime"] = DateTime.Now.ToShortTimeString();
return View(myProduct);
}
}

Here we simply create a controller and pass a product object to the view for display. viewbag and viewdata are also displayed. Previous notes on these two attributes are used for data transmission between the Controller and the view. Which of the following parameters about viewbag and viewdata is used for transmission depends on your preferences, it is not said that viewbag must be better than viewdata.

Step 3: Add a strong-type view -- index. cshtml. The comparison in front of how to add a strong-type view is described. If you are not clear, you can go to the previous notes. View:

@model Razor.Models.Product
@{
Layout = null;
}
<!DOCTYPE html>
@{
ViewBag.Title = "Index";
}
<title>@ViewBag.Title</title>
<body>
<div>
Name:@Model.Name </div>
</body>

Step 4: To make it easy for us to run the program, we change the route settings after the program runs to our current controller. The routing settings are carried out in global. asax, as shown below:

Public static void registerroutes (routecollection routes)
{
Routes. ignoreroute ("{resource}. axd/{* pathinfo }");

Routes. maproute (
"Default", // route name
"{Controller}/{action}/{ID}", // URL with Parameters
New {controller = "product", Action = "Index", id = urlparameter. optional} // default value of the Parameter
);

}

Like me, the beginner MVC should not be troubled by the routing system here, and there is no need to worry about it. There will be a special chapter to illustrate the routes System (Routing System ). Now it's okay to change it.

Step 5: Let's take a look at the razor view we created. The following is a part:

First, let's focus on the statements in the red box, @ model razor. Models. Product. Because we have created a strongly typed statement, there is such a statement. If it is not a strongly typed statement, there is no. "@ Model" is used to specify the model type to be presented for a specific view. Note that the model here is m in lower case. When we reference a model object, we use @ model, Capital M. The running program displays name: kayak.

Next we will go to index. add code in cshtml, and click "<H2> name: @ model. add the following statement for name </H2>: Time View rendered: @ datetime. now. tow.timestring (). Note that @ is used here. We need to get used to this method. Here we use the @ model. attribute name, so that the attribute value is written on the page. @ The symbol is used to process complex code quickly.

If we don't want to display any HTML tags, but just want to display text, we can write "@:" followed by the information we want to display. After running the program, you can check the source file to see if no HTML Tag is added. Of course, if you want to add many lines of text, you can use <text> </text>, which is equivalent to adding "@:" To each line "@:".

3. Use layouts

There is a _ layout. cshtml under views/shared. When we create a view, the checkbox with the layout selected is also displayed in the dialog box. By default, MVC looks for _ viewstart. cshtml. on this page, I can decide which layouts to introduce. Note that there is another convention: A View named after an underscore will not be directly presented to the client, and requests directly in the URL will not be returned to the client. _ Layout. cshtml is equivalent to masterpage. Below is a _ layout. cshtml:

<!DOCTYPE html>
<title>@ViewBag.Title</title>
<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>
<body>
@RenderBody()
</body>

Here @ viewbag. the title definition can also be regarded as an agreement. When we reference this _ layout in other views. cshtml, which is equivalent to a placeholder, can dynamically display the title based on our needs. This method replaces palceholder. use renderbody () in razor to present the body of our view, because when we introduce _ layout. when cshtml is used, we write all the body parts. Other CSS and JS files to be introduced can be stored in _ layout. add it in cshtml, so that you do not need to add it again in other views that have been introduced to it. Of course _ layout. cshtml is optional. You can choose not to use _ layout. cshtml. however, we need to add @ {layout = NULL;} in the view. If you do not specify this, _ viewstart will be referenced by default. cshtml.

Today's notes are made here. I just learned MVC and took notes to consolidate and deepen my understanding. Of course, I am very happy to be able to help beginners who are just like me a little bit. There must be some inaccuracy and errors in the notes. Please help me with your guidance. Thank you!
Wish the passing friends a smooth job!

Good night!

Related Article

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.