ASP. NET mvc4.0 Getting Started Guide-Add a view

Source: Internet
Author: User

In this section, you need to modify the helloworldcontroller class to use the view template file to generate the HTML returned to the client browser through a clean and elegant encapsulation.

You will create a view template file using 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 use the C # language to create the HTML to be output. When you use razor to write a view template file, you can minimize the number of characters and keyboard percussion required, and implement a fast and smooth coding workflow.

The index method in the Controller class returns a hard-coded string. Return a view object by changing the index method, as shown in the following example.Code:

 
 PublicActionresult index (){ReturnView ();}

The index method above uses a view template to generate an HTML and return it to the browser. The Controller method (also called Action Method). The above index method generally returns an actionresult (orActionresultThe inherited type), rather than the original type, such as string.

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

AppearsAdd ViewDialog box. Retain the default value, and clickAddButton

You canSolution Resource ManagerThe mvcmovie \ views \ helloworld folder and the created mvcmovie \ view \ helloworld \ index. cshtml file are displayed:

The created index. cshtml file is displayed:

 
@ {Viewbag. Title="Index";}<H2> index </H2>

Add the following HTML after the <H2> tag: <p> return from our view template! </P>

CompleteMvcmovie \ helloworld \ index. cshtmlFile is as follows.

@ {Viewbag. Title = "Index" ;}< H2> index </H2> <p> returned from our view template! </P>

RunProgramAccess the Hellworld controller http: // localhost: 5279/helloworld /. The index method in the controller does not do a lot of work, just executeReturn view () Statement, specifying the template file to respond to browser requests. Because you have not specified the template file name, ASP. net mvc uses\ Views \ helloworldDirectoryIndex. cshtmlView File.

Looks good. However, pay attention to the browser title bar "index-my ASP. net mvc application" and a large link at the top of the page "place your logo here ". At the bottom of the link is the registration and login link, followed by the home page, about and contact information page Link. 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 commonly used on each page. Although each page appears in the application, it is defined only once in the project ,. Go to Solution Explorer/Views/sharedDirectory, open_ Layout. cshtmlFile. This file is called a layout page, shared as a shell, used by all other pages.

The layout template allows you to specify a specific HTML container to layout the entire site, which is defined in one place and applied on multiple pages of the site. Find@ Renderbody ()Line.RenderbodyIt is a placeholder in the view page you created, and the line is interrupted on the layout page. For example, if you select the "about" link, \ home \ about. cshtml view inRenderbodyMethod.

In the layout template, modify the site title line from "place your logo here" to "MVC movie ".

<DivClass="Float-left"><PClass="Site-title">@ Html. actionlink ("MVC movie", "Index", "home ")</P></Div>

Replace the title content with the following mark:

<Title>@ Viewbag. Title-movie Application</Title>

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

 
Now, let's modify the index view title.

OpenMvcmovie \ views \ helloworld \ index. cshtmlFile. There are two items to be modified: first, the text displayed in the browser title bar, and second, the text displayed in the level-2 Title (<H2> element. You can modify the two parts a little differently, so that you can differentiate which part corresponds to the application.

 
@ {Viewbag. Title="Homepage";}<H2> my homepage </H2>

Code settingsViewbagOfTitleAttribute to specify the display content of the HTML title. If you view the source code of the layout template, you will notice that the template is<Title> the value is used<Head>. UseViewbag, you can easily pass other parameters between the view template and the layout file.

Run the program and browseHttp: // localhost: XX/helloworld. You will find that the page title, level-1 title, and level-2 Title have changed. (If you cannot see the changes in the browser, you may see the cached content, use Ctrl + F5 to force the browser to load data from the server to the client ). The browser Title consists of two parts: the first one we set in the index. cshtml view TemplateViewbag. title, and then "-movie application" set in the layout file ".

Note thatIndex. cshtmlHow is the view template file content consistent_ Layout. cshtmlView template merging to form a single HTML response and return it to the browser. The layout template makes it easy to modify the application to all pages of your application.

In the above example, we seldom use hard encoding. This MVC application has a view, and you have created a controller, but there is no model. Soon we will discuss how to create a database and obtain model data from it.

Transmit data from the Controller to the view

Before creating a database and talking about the model, let's talk about transferring information from the Controller to the view. The Controller class is called to respond to the request for entering the URL. Write code in the Controller class to process browser input requests, obtain data from the database, and decide what type of response is sent back to the browser request. View templates from controllers are used to generate and format HTML responses to browsers.

The Controller is responsible for providing any data or objects required to the view template to generate a response to the browser. Best Practice: View templates should not process business logic or directly interact with databases. The view template should only process the data provided by the Controller. Keeping relationships isolated helps make your code clean, testable, and easy to maintain.

Currently,In the helloworldcontroller classWelcomeThe method is to use the name and num parameters to directly output the value to the browser. Let's change the controller and use a view template to replace the Controller with a string to respond to requests. The view template will produce a dynamic response, which means you need to pass a view template that is accessibleViewbagObject.

Return toHelloworldcontroller. CSFile, modifyWelcomeMethod to add the message and num values to the viewbag object. Viewbag is a dynamic object, which means you can put anything you want into it. This object has no defined attributes before you put anything in it. ASP. net mvc model binding mechanism automatically maps the named parameters in the address bar query string to parameters in your method. CompleteShows helloworldcontroller. CS: 

PublicActionresult welcome (StringMessage,IntNum =1) {Viewbag. Message=Message; viewbag. Num=Num;ReturnView ();}

The viewbag object containing data will be automatically passed to the view.

Next, you need a welcome view template. In the generate menu, select generate mvcmovie to ensure that the project is compiled.

Right-click the welcome method and select add view to keep the default value.

SetWelcome. cshtmlReplace <H2> welcome </H2> with the following content.

<Ul>@ (IntI =0; I <viewbag. Num; I ++){<Li> @ viewbag. Message </LI>}</Ul>

Run the command to view the effect.

Now the data is passed to the Controller through model binding from the address bar. The Controller packs 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 transmit data from the Controller to the view. Later, we will use the view model to transmit data. Compared with viewbag, the view model delivers better data.

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

 


AllArticleNavigation

This series contains 10 articles translated from ASP. net mvc4 official tutorial, due to the concise description of this series of articles, the length is moderate, from an example to explain, the full text finally completed a small system for managing movies, very suitable for beginners ASP.. Net mvc4.

The original article is for 9 articles, and the translator splits 6th of them into 2

1. Introduction to ASP. NET mvc4

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/03/2800210.html

2. Add a controller

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/04/2801949.html

3. Add a view

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-view

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/04/2801988.html

4. Add a model

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/05/2803012.html

5. Access the data model from the Controller

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/05/2803429.html

6. view the Edit Method and edit View

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/05/2804100.html

Http://www.cnblogs.com/seawaving/archive/2012/12/06/2804590.html

7. Add fields for the movie model and database table

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-new-field-to-the-movie-model-and-table

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/06/2805401.html

8. Add verification for the model

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/06/2806322.html

9. view the detail and delete Methods

· Original address: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-details-and-delete-methods

· Address: http://www.cnblogs.com/seawaving/archive/2012/12/10/2811064.html

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.