ASP. NET MVC4.0 Official tutorial Getting Started Guide three--Add a view

Source: Internet
Author: User

ASP. NET MVC4.0 Official tutorial Getting Started Guide three--Add a view

In this section, you need to modify the Helloworldcontroller class to use the view template file, which generates a clean and elegant wrapper to return the HTML to the client browser.

You will create a view template file that uses the Razor view engine introduced by ASP. NET MVC 3. The Razor view template file uses the. cshtml file extension and provides an elegant way to create the HTML that you want to output using the C # language. When writing a view template file with razor, the required number of characters and keystrokes is minimized and a fast and smooth coding workflow is achieved.

The index method currently in the Controller class returns a hard-coded string. Changing the index method returns a View object, such as the following sample code:

Public ActionResult Index () {    return View ();}

The index method above uses a view template to generate an HTML return to the browser. The controller's method (also known as action method), such as the index method above, typically returns a ActionResult (or type inherited from ActionResult), rather than the original type, such as a string.

In this project, you can use the index method to add a view template. To do this, right-click in the index method, and then click Add View.

The Add View dialog box appears. Leave the default values and click the Add button

You can see the Mvcmovie\views\helloworld folder and the mvcmovie\view\helloworld\index.cshtml file that has been created in Solution Explorer :

The index.cshtml file that has been created is displayed:

@{    "Index";}    

Add the following html:<p> after the

The complete mvcmovie\helloworld\index.cshtml file is shown below.

@{viewbag.title = "Index"; }

Run the program and access the Hellworld controller http://localhost:5279/HelloWorld/. The index method in the controller does not do much work, just the executionreturn View()语句,指定使用模板文件来响应浏览器请求。因为你没有指定使用的模板文件名称,ASP.NET MVC默认使用\Views\HelloWorld目录下的Index.cshtml视图文件。

It looks pretty good. Note, however, that the browser title bar "index-My ASP. NET MVC application" and a large link at the top of the page "place your logo here". Below the link is the sign up and sign in link, and then down to the homepage, about and contact page links. Let's modify these.

Modify view pages and layout pages

First, you want to modify the title "Place Your Logo here" at the top of the page. This text is common in each page. Although it appears in every page of the app, it is actually defined only once in the project. In Solution Explorer, navigate to the /views/shared directory, and open the _layout.cshtml file. The file is called a layout page, shared as a shell, and used by all other pages.

Layout templates allow you to specify a specific HTML container to lay out the entire site, defined in one place, and applied across multiple pages of the site. Locate the @RenderBody() row. RenderBodyis a placeholder in the view page that you created, and breaks the line on the layout page. For example, if you select the About link, the \home\about.cshtml view is rendered in the RenderBody method.

Modify the site header row in the layout template, and change the "place your logo here" to "MVC movie."

<divClass="Float-left"><pclass="Site-title">@ Html.ActionLink ("MVC movie", "Index", "Home")</p></div>

Replace the header content with the following tags:

<title>@ViewBag. title-movie apps </title>

Run the program, and note that the "MVC movie" is now displayed. Click on the "about" link and you will find that the page also shows "MVC movie". We change it once in the layout template, and all pages in the site are changed to the new title.


Now, let's modify the title of the Index view.

Open the mvcmovie\views\helloworld\index.cshtml file. There are two places to modify: First, the text displayed in the browser's title bar, followed by the level two heading (<H2> element). You can make the two changes slightly different so that you can distinguish which part of the application corresponds to which.

@{    " home ";}    

ViewBagThe code Title indicates the display of the HTML caption by setting the property. If you look at the source of the layout template, you will notice that the template<title>元素中使用该值作为 ViewBag,你可以容易地在视图模板和布局文件间传递其他参数。

Run the program and browse Http://localhost:xx/HelloWorld. You will find that the title of the Browse page, the first title, the level two title has changed (if you do not see the change in the browser, then you may be looking at the cache content, using CTRL+F5 force the browser to load data from the server to the client). The browser title consists of two parts, the first of which we set in the Index.cshtml view template.ViewBag.Title,然后是在布局文件中设置的“-电影应用程序”。

Also note how the index.cshtml View template file content is merged with the _layout.cshtml view template to form a single HTML response back to the browser. Layout templates make it easy to apply changes to all pages of your application.

In the example above we have very little data that is hard coded. This MVC application has a view, and you have created the controller, but there is no model yet. Soon, we'll cover how to create a database and get model data from it.

Passing data from the controller to the view

Before we create the database and talk about the model, let's talk about passing information from the controller to the view. The controller class is called to respond to input URL requests. Write code in the Controller class, process the browser input request, fetch the data from the database, and decide what type of response is sent back to the browse request. The view template from the controller is used to generate and format the HTML response to the browser.

The Controller is responsible for providing any data or objects needed to the view template to generate a response to the browser. The best practice is that the view template should not handle business logic or interact directly with the database. The view template should only handle the data that the controller provides to it. Keeping your relationships isolated helps make your code clean, testable, and easy to maintain.

CurrentlyHelloWorldController类中的Welcome方法是用name和num参数,直接输出值到浏览器。让我们改变控制器,使用视图模板来替代控制器使用字符串响应请求。视图模板将生产一个动态响应,意味着你需要传递一个视图模板可访问的ViewBag对象。

Return to the HelloWorldController.cs file, modify the Welcome method, and add the message and NUM values for the ViewBag object. ViewBag is a dynamic object, which means that you can put anything you want to go in; The object does not have a defined property until you put anything in it. The ASP. NET MVC model binding mechanism automatically maps named parameters in the Address bar query string to the parameters in your method. The complete HelloWorldController.cs is as follows:

        Public ActionResult Welcome (1)        {             message; Viewbag.num =return     

The ViewBag object that contains the data is now automatically passed to the view.

Next, you need a welcome view template. From the Build menu, choose Generate Mvcmovie to ensure that the project is compiled.

Then right-click in the Welcome method, select Add view, leave default, Add.

Replace welcome.cshtml file with the following:

<ul>@for (0; i < viewbag.num; i++) {    <li> @ViewBag .message</li>}</ul> 

Run the view effect.

The data is now passed from the address bar to the controller through model bindings. The controller packages the data into the ViewBag object and passes the object to the view. The view displays the data as HTML to the user.

In the above example, we use the ViewBag object to pass data from the controller to the view. Later in the study, we will use the view model to pass the data. View mode delivers better data than viewbag

This is a model of a way, but not a database way. Let's learn and create a database of movies.

ASP. NET MVC4.0 Official tutorial Getting Started Guide three--Add a view

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.