ASP. NET Core Chinese Document chapter II Guide (4.3) add View

Source: Internet
Author: User

Original: Adding a view
Rick Anderson
Translation: Chinese (initial)
Proofreading: Zhao Liang (Sad Dream), Gao Song (Jack), Lou Yu (lyrics), Huden (Seay), Yao Ayong (Dr.yao)

This section modifies the HelloWorldController class to cleanly encapsulate the process of generating HTML responses for clients using the Razor view template file.

You can use the Razor view engine to create a view template. Files based on the Razor view template use . cshtml as their extension and gracefully output HTML in C #. Writing a view template with Razor can reduce the number of characters and number of keystrokes, and make the workflow fast and flexible.

Currently, the methods in the Controller class return a string of Index hard-coded strings. Modify the method to return the view object as shown in the following code Index :

public IActionResult Index(){    return View();}

In the example above, the Index method generates an HTML response to the browser with a view template. The Controller method (also known as the action method), such as the Index method above, usually returns IActionResult (or derives from ActionResult the class) rather than the primitive type as the string.

    • Right- Click the Views folder, select Add > New folder (Add > Create new Folders), and then name the folder HelloWorld.

    • Right-click on the views/helloworld (view/helloworld) folder and select Add > New Item (add New Item)

    • In the Add new item-mvcmovie -Mvcmovie dialog box:

    • In the search box at the top right, enter the keyword view

    • Click on MVC View page (MVC views pages)

    • In the name box, leave the default index.cshtml

    • Click Add

Replace the Razor view file views/helloworld/index.cshtml with the following code:

@{    ViewData["Title"] = "Index";}Index<p>Hello from our View Template!</p>

Navigate to http://localhost:xxxx/HelloWorld . HelloWorldController Index Way to do only one thing--run the return View(); statement to direct the Controller method to render the final response result for the browser using the specified view template file. Because the file name of the view template used is not explicitly specified, MVC uses the index.cshtml view file in the /views/helloworld folder by default. Displays the hard-coded string "Hello from our view template!" in the view.

If the browser form is small (for example, on a mobile device), you may need to toggle (click) The Bootstrap navigation button on the top right to see Home, about, contact, Register and Log in these links.

Change the View and layout page

Click the menu link (mvcmovie,Home , and about). Each page displays the same menu layout. The menu layout is implemented in the views/shared/_layout.cshtml file. Open the views/shared/_layout.cshtml file.

The layout template allows you to specify HTML container layouts for sites in one place and then use them in multiple pages under the site. Find @RenderBody() the line. RenderBodyis a placeholder that is where all of your specified views are displayed, "wrapped in" in the layout page. For example, If you click on the About link, the views/home/about.cshtml view is RenderBody rendered within the method.

Changes the content of the caption element. In the layout template, the anchor ( i.e. A label, translator note ) text is changed to "MVC Movie", the controller will be Home changed Movies , as highlighted below:

<! DOCTYPEHtml>    <metacharset="Utf-8" />    <metaname="Viewport"content="Width=device-width, initial-scale=1.0" />    <title>@ViewData ["Title"]-Movie App</title>    <!--manual highlighting --    <environmentnames="Development">        <linkrel="stylesheet"href="~/lib/bootstrap/dist/css/bootstrap.css" />        <linkrel="stylesheet"href="~/css/site.css" />    </environment>    <environmentnames="Staging,production">        <linkrel="stylesheet"href="Https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css"asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"asp-fallback-test-class="Sr-only"asp-fallback-test-property="Position"asp-fallback-test-value="Absolute" />        <linkrel="stylesheet"href="~/css/site.min.css"asp-append-version="true" />    </environment><body>    <divclass="NavBar navbar-inverse navbar-fixed-top">        <divclass="Container">            <divclass="Navbar-header">                <buttontype="button"class="Navbar-toggle"data-toggle="Collapse"data-target=". Navbar-collapse">                    <spanclass="Sr-only">Toggle Navigation</span>                    <spanclass="Icon-bar"></span>                    <spanclass="Icon-bar"></span>                    <spanclass="Icon-bar"></span>                </button>                <aasp-controller="Movies"asp-action="Index"class="Navbar-brand">MVC Movie</a>  <!--manual highlighting --            </div>            <divclass="Navbar-collapse collapse">                <ulclass="Nav Navbar-nav">                    <li><aasp-controller="Home"asp-action="Index">Home</a></li>                    <li><aasp-controller="Home"asp-action="About">About</a></li>                    <li><aasp-controller="Home"asp-action="Contact">Contact</a></li>                </ul>@await Html.partialasync ("_loginpartial")</div>        </div>    </div>    <divclass="Container body-content">@RenderBody () />        <footer>            <p>&copy;2016-mvcmovie</p>        </footer>    </div>    <environmentnames="Development">        <scriptsrc="~/lib/jquery/dist/jquery.js"></script>        <scriptsrc="~/lib/bootstrap/dist/js/bootstrap.js"></script>        <scriptsrc="~/js/site.js"asp-append-version="true"></script>    </environment>    <environmentnames="Staging,production">        <scriptsrc="Https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"asp-fallback-src="~/lib/jquery/dist/jquery.min.js"asp-fallback-test="Window.jquery">        </script>        <scriptsrc="Https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"asp-fallback-test="Window.jquery&&Window.jQuery.fn&&Window.jQuery.fn.modal ">        </script>        <scriptsrc="~/js/site.min.js"asp-append-version="true"></script>    </environment>@RenderSection ("Scripts", Required:false)</body>

Warning
We have not implemented the Movies controller, so if you click on the link, you will get 404 error (File not found).

Save and click on the About link. Notice how each page shows the Mvc Movie link. Change only once in the layout template, and all pages in the site display new links and new titles.

Take a look at the views/_viewstart.cshtml file:

@{    Layout = "_Layout";}

The views/_viewstart.cshtml file introduces the views/shared/_layout.cshtml file into each view. You can use Layout properties to set different layout views, or set them null so that layout views are not used.

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

Open views/helloworld/index.cshtml . Here are 2 places to change:

    • Title text that appears on the browser
    • Secondary headings ( elements).

You can change it a little bit, so you can see which code changes where the application is.

@{ ViewData["Title"] = "Movie List"; //手动高亮}My Movie List <!--手动高亮--><p>Hello from our View Template!</p>

ViewData["Title"] = "Movie List";set the Title property of Viewdatadictionary to "Movie list" in the code above. Titleproperty is used in the layout page of the <title> In the HTML element:

<title>@ViewData["Title"] - Movie App</title>

Save and refresh the page. Note that the browser title, main title, and subtitle are changed (if you don't see the change, you might press Ctrl+f5 to force refresh in the browser because of the cache). The browser title is made up of the ViewData["Title"] "-Movie App" combination that we set up in the Index.cshtml view template and on the layout page.

Also note how the contents of theindex.cshtml view template are merged with the Views/shared/_layout.cshtml view template, and how an HTML response is sent to the browser. Layout templates are very easy to modify for all pages in the application. For more information, please refer to: Layout.

However, we have this "data" (the message in this example "Hello from US View template!" ) or hard-coded. The MVC application already has a "V" (View), we have created a "C" (Controller), but there is no "M" (Model). Next we'll quickly show you how to create a database and search for model data from it.

Passing data from the controller to the view

Before we talk about databases and models, let's talk about passing information from the controller to the view. The controller class is called when it responds to incoming URL requests. The controller class is the place to write code to process incoming browser requests, retrieve data from the database, and ultimately decide what type of response to send back to the browser. You can then use the view template to generate and format HTML in the controller to respond to the browser.

The Controller is responsible for providing any data or objects needed so that the view template renders a response to the browser. Best practice: A view template should not execute business logic or interact directly with the database, but should only use the data that the controller provides to it. Keeping this "separation of concerns" helps keep your code neat, testable, and easier to maintain.

Currently, HelloWorldController the methods in the class Welcome accept one name and one ID parameter, and then output the value directly to the browser. Instead of having the controller use a string to render the response, let's change the controller to use the view template. The view template generates a dynamic response, which means that the appropriate data needs to be passed to the view through the controller to generate the response. To do this, you can have the controller place the Dynamic Data (parameters) required by the view template in a ViewData dictionary that can then be accessed by the View stencil.

Back to the HelloWorldController.cs file, Welcome add one Message and the value in the method to the NumTimes ViewData dictionary. A ViewData dictionary is a dynamic object, which means that you can add any data you want. Before you add something to it, the ViewData object has no properties defined. The MVC model binding system automatically maps the named parameters (and) of the query string in the address bar name numTimes into your method parameters. The complete HelloWorldController.cs file looks like this:

using Microsoft.AspNetCore.Mvc;using System.Text.Encodings.Web;namespace MvcMovie.Controllers{    public class HelloWorldController : Controller    {        public IActionResult Index()        {            return View();        }        public IActionResult Welcome(string name, int numTimes = 1)        {            ViewData["Message"] = "Hello " + name;            ViewData["NumTimes"] = numTimes;            return View();        }    }}

ViewDataThe Dictionary object contains the data that will be passed to the view. Next, you need a Welcome view template.

    • Right-click on the views/helloworld folder and click Add > new Item (Add > New Item).

    • In the Add new item-mvcmovie -Mvcmovie dialog box

    • Enter the keyword view in the search box in the upper right corner

    • Click on MVC View page (MVC views pages)

    • In the Name box, enter welcome.cshtml

    • Click Add

Create a loop in the welcome.cshtml view template to display "Hello" NumTimes . Completely replace the contents of views/helloworld/welcome.cshtml with the following code:

@{    ViewData["Title"] = "About";}Welcome<ul>    < (int)ViewData["NumTimes"]; i++)    {        <li>@ViewData["Message"]</li>    }</ul>

Save the changes and open the browser to access this address:

http://localhost:xxxx/HelloWorld/Welcome?name=Rick&numtimes=4

The data is fetched from the URL and passed to the controller using the model binder. The controller encapsulates the data into a ViewData dictionary and passes the object into the view. The view then renders the data in HTML to the browser.

In the example above, we use a ViewData dictionary to pass data from the controller to the view. In a later tutorial, we will use the view model to pass data from the controller to the view. Methods of passing data in a view model are generally ViewData more popular than dictionaries. View Dynamic V strongly Typed views for more information.

Well, it's kind of a model of "M", but it's not a database model anyway. Let's create a movie database with what we've learned.

Back to Catalog

Reference page:

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-view-start.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-import-view.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-razor-taghelpers.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-edit-form.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-identity.html

ASP. NET Core Chinese Document chapter II Guide (4.3) add 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.