"MVC5" 3. Add a View

Source: Internet
Author: User
Tags actionlink

In this section you will modify the process used by the Helloworldcontroller class to generate an HTML response client using the view template file in a neat package.

Create a view template file using the view engine. Based on the Razor view template has. cshtml file extension and offers to use C #创建HTML输出一种优雅的方式. Razor the number of characters and keys needed to write a view template, and the ability to quickly and flexibly work on the workflow.

The current index method returns a string that is hard-coded in the controller class for the message. Changing the index method returns a View object, as shown in the following code:


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

The method of the above index is to use a view template to generate an HTML response to the browser. The controller's method (also known as the method of action), such as the index method above, typically returns a ActionResult (or derived from the ActionResult Class), not a string of the original type.
Right-clickViews\helloworldFolder and clickADD, and then clickMVC 5 View Page with (Layout Razor)



In the Specify Project dialog box, in Specify name, enter an index, and then click OK.




In the Select a Page Layout dialog box, accept the default _layout.cshtml click OK.




In the dialog box above, view \ Shared folder is selected in the left pane. If you have a custom layout file in another folder, you can select it. We'll discuss the layout file in a later tutorial

The mvcmovie\views\helloworld\index.cshtml file is created.




Add the following code.


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


Right-click in the browser to select the view index.cshtml file.




You can also right-click the index.cshtml file and select Page view. Check out the page review tutorials for more information.


In addition, run the application and browse to the HelloWorld controller (Http://localhost:xxxx/HelloWorld). The index method in your controller does not do much work; it simply returns the statement (view bag), and it specifies that the method should use a view template file to render the response to the browser. Because you do not explicitly specify the name of the view template file by using ASP. NET MVC, the default view \ HelloWorld folder uses the index.cshtml view file. The following picture shows the string from our view template "Hello from USview template!" Hard-coded in the view.




It looks good. However, notice that the title bar of the browser displays "My ASP.", at the top of the page The big link says "application name." "It depends on the small make your browser window, you may need to click on the three columns in the top right corner to see the home, Contacts, registration and login links.


Change the View and layout page

First, you change the "Application name" link at the top of the page. The text is common on every page. It is actually just a place to implement in a project, even if it appears on every page of the application. Go to the/views/shared folder to open the _layout.cshtml file in Solution Explorer. This file is called a layout page, which is used in shared folders and all other pages.




Layout templates allow you to specify HTML layouts in a local site and then apply them on multiple pages in your site. Locate the @renderbody () line. Renderbody is a placeholder for a page layout that is created to display a "wrapper" on a specific page of all views. For example, if you select the link, the comments \ Home about.cshtml view is rendered in the Renderbody method.

Change the contents of the caption element. Change the connection in the layout template from "Application name" to "MVC movie", from home to the controller of the movie. The complete layout file looks like this:


<! DOCTYPE html>

Run and notify the app, now say "MVC Movie". Click on the link to see how the page shows "MVC Movie", too. We are able to make changes once in the layout template, and all pages on the site reflect the new title.




When we first created the views\helloworld\index.cshtml file, it contains the following code:


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


The above is the Explicted Razor Code Settings page layout. Review commentsviews\_viewstart.cshtmlFile, which contains the same razor tag. Aboutviews\_viewstart.cshtmlThe file defines all views that will use the common layout, so you can comment on or remove the code from the viewviews\helloworld\index.cshtml File.


@*@{    Layout = "~/views/shared/_layout.cshtml";} *@@{    viewbag.title = "Index";} 


You can use layout properties to set different layout views, or to set them to empty, so you do not use layout files.

Now, let's change the title of the indexed view.

Open the mvcmovie\views\helloworld\index.cshtml view HelloWorld. There are two places to make changes: first, the text that appears in the browser title, and then in the second heading (< hydrogen > Element). You will make them slightly different, so you can see which code changes the part of the application.


@{    viewbag.title = "Movie List";} 


Displays the code for the HTML caption display, the above set of ViewBag Object caption properties (This is in the Index.cshtml view template). Note that the layout template (views\shared\_layout.cshtml ) uses this value in the title> element as we modify the previous HTML


<! DOCTYPE html>


Using the ViewBag method, you can easily pass other parameters between the view template and your layout file.

Run the application. Note that the browser title, main title, and minor title have changed. (If you don't see your browser's changes, you might see the contents of the cache.) Press CTRL + F5 browser Force to load the response from the server. The browser title is created with ViewBag. Title we set the index.cshtml view template and the additional "movie app" in the layout file.

Also note that the content in the Index.cshtml view template is sent to the browser with the _layout.cshtml view template and a single HTML response merge. The layout template makes it easy to make changes to all the pages in your application.





We have a little bit of "data" (in this case, from our view template "Hello"!) Message) is hard-coded, but. The MVC application has a "V" (see) you already have a "C" (Controller), but there is no "M" (model). Soon, we will walk through how to create a database and retrieve model data from it.


Passing data from the controller to the view

Before we go to a database and talk about models, let's talk about passing information from the controller to the view. Invokes the Controller class in response to a request for an incoming request. A controller class is the code that you write, processes incoming browser requests, retrieves data from the database, and ultimately determines what type of response is sent back to the browser. View templates can be used to generate and format HTML responses from the controller to the browser.

The Controller is responsible for providing any required data or objects to view the view template to respond to the browser. Best practice: View templates should not execute business logic or interact directly with the database. Instead, the view template should only work with the data that the controller provides to it. Keeping this "separation of concerns" helps keep your code clean, testable, and easier to maintain.

Currently, the Helloworldcontroller class Welcome action method requires a name and a numtimes parameter and outputs the value of the direct browser. Instead of having the controller render this response as a string, let's change the controller using the view template instead. The view template produces a dynamic response, which means that you need to generate a response from the controller to the view with the appropriate data bits. You can access the view template's requirements by using the controller to move the Dynamic Data (parameters) in the ViewBag object's view template.

Go back to the Helloworldcontroller.cs file and modify the Welcome method to add a message to the Numtimes value ViewBag object. ViewBag is a dynamic object, which means you can put anything you want it; ViewBag object has no defined properties until you put something inside. Asp. NET MVC model binding system automatically maps the named parameters (name and numtimes) from the address bar in the query string to your method parameters.

The complete Helloworldcontroller.cs file looks like this:


Using system.web;using system.web.mvc;namespace mvcmovie.controllers{public    class Helloworldcontroller: Controller    {public        actionresult Index ()        {            return View ();        }        Public ActionResult Welcome (string name, int numtimes = 1)        {            viewbag.message = "Hello" + name;            Viewbag.numtimes = Numtimes;            return View ();}}    }


The data contained in the ViewBag object is now passed to the view automatically. Next, you need a popular view template! On the Build menu, choose Build Solution (or press CTRL + Shift + B) to make sure the project compiles. Right-click the View \ HelloWorld folder and click Add, and then click View Page MVC 5 (Layout Razor).




In the Specify Name dialog box, enter welcome, and then click OK.

In the Select a Page Layout dialog box, accept the default _layout.cshtml click OK.





mvcmovie\views\helloworld\welcome.cshtml the file is created.

Replace the tag in the welcome.cshtml file. You will create a loop that says "Hello" because the user says it should. The complete welcome.cshtml file is shown below.


@{    viewbag.title = "Welcome";} 


Run the application and browse to the following URL:

Http://localhost:xx/HelloWorld/Welcome?name=Scott&numtimes=4

Now the data is from the URL and passed to the controller using the model binder. The controller's data is encapsulated into an object through the ViewBag object view. The view data is then displayed as an HTML user.




In the example above, we use the ViewBag object to pass data from the controller to the view. In the tutorial, we will use a view model to pass data from the controller to the view. The method of the view model to pass the data is generally the preferred method of the view package. View blog entries for dynamic v-type comments for more information.

Well, this is a model of "M", but not a database type. Let's take what we've learned and create a movie database.









"MVC5" 3. 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.