在添加View之前,之前的页面是下面这个样子,需要注意的是浏览器标题,以及浏览器的内容

https://docs.asp.net/en/latest/tutorials/first-mvc-app/adding-view.html

In this section you’re going to modify the HelloWorldController class to use Razor view template files to cleanly encapsulate the process of generating HTML responses to a client.

You’ll create a view template file using the Razor view engine.

Razor-based view templates have a.cshtml file extension, and provide an elegant way to create HTML output using C#.

Razor minimizes the number of characters and keystrokes键盘输入 required when writing a view template, and enables a fast, fluid流畅的 coding workflow.

Currently the Index method returns a string with a message that is hard-coded in the controller class.

Change the Index method to return a View object, as shown in the following code:

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

The Index method above uses a view template to generate an HTML response to the browser.

Controller methods (also known as action methods), such as the Index method above, generally return an IActionResult (or a class derived from ActionResult), not primitive types like string.

  • Right click on the Views folder, and then Add > New Folder and name the folder HelloWorld.
  • Right click on the Views/HelloWorld folder, and then Add > New Item.
  • In the Add New Item - MvcMovie dialog
    • In the search box in the upper-right, enter view
    • Tap MVC View Page
    • In the Name box, keep the default Index.cshtml
    • Tap Add

Replace the contents of the Views/HelloWorld/Index.cshtml Razor view file with the following:

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

Navigate to http://localhost:xxxx/HelloWorld.

The Index method in the HelloWorldController didn’t do much work; it simply ran the statement return View();,

which specified that the method should use a view template file to render a response to the browser.

Because you didn’t explicitly specify the name of the view template file to use, MVC defaulted to using the Index.cshtml view file in the /Views/HelloWorld folder.

The image below shows the string “Hello from our View Template!” hard-coded in the view.

需要注意的是,标题和内容都变化了

下面的是新的界面显示

If your browser window is small (for example on a mobile device), you might need to toggle (tap) the Bootstrap navigation button in the upper right

to see the to the HomeAboutContactRegister andLog in links.

Changing views and layout pages

Tap on the menu links (MvcMovieHomeAbout).

Each page shows the same menu layout.

The menu layout is implemented in the Views/Shared/_Layout.cshtml file.

Open theViews/Shared/_Layout.cshtml file.

Layout templates allow you to specify the HTML container layout of your site in one place and then apply it across multiple pages in your site.

Find the @RenderBody() line. RenderBody is a placeholder占位符 where all the view-specific pages you create show up, “wrapped” in the layout page.
RenderBody 是一个占位符,是你所有指定视图的显示位置,“包裹在”布局页内。

For example, if you select the About link, the Views/Home/About.cshtml view is rendered inside the RenderBodymethod.

例如,点击 About 链接, Views/Home/About.cshtml 视图就会在 RenderBody 方法内渲染。

Change the contents of the title element.

Change the anchor text in the layout template to “MVC Movie”

and the controller from Home to Movies as highlighted below:

<title>@ViewData["Title"] - Movie App</title>     //这里设置的是layout整体布局的Title,所有使用layout布局的,都会受这个影响

<a asp-controller="Movies" asp-action="Index" class="navbar-brand">Mvc Movie</a>    //这行是设置MvcMovies的链接跳转

Warning:

We haven’t implemented the Movies controller yet, so if you click on that link, you’ll get a 404 (Not found) error.

Save your changes and tap the About link. Notice how each page displays the Mvc Movie link.

We were able to make the change once in the layout template and have all pages on the site reflect the new link text and new title.

没有修改之前

修改之后的    标题变为Movie App了

点击MvcMovie的时候,自动跳转到http://localhost:63126/Movies 【没有修改之前,访问的是http://localhost:63126】

Examine the Views/_ViewStart.cshtml file:

@{
Layout = "_Layout";
}

The Views/_ViewStart.cshtml file brings in the Views/Shared/_Layout.cshtml file to each view.

You can use the Layout property to set a different layout view, or set it to null so no layout file will be used.  //这里的设置null,应该是把后面发字符串改为空字符串

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

Open Views/HelloWorld/Index.cshtml. There are two places to make a change:

  • The text that appears in the title of the browser    出现在浏览器上的标题文本
  • The secondary header (<h2> element).                  二级标题

You’ll make them slightly different so you can see which bit of code changes which part of the app.

@{
ViewData["Title"] = "Movie List"; //这里设置的Title,最终会应用到浏览器的标题上
} <h2>My Movie List</h2> <p>Hello from our View Template!</p>

ViewData["Title"] = "Movie List";

in the code above sets the Title property of the ViewDataDictionary to “Movie List”.

The Title property is used in the <title> HTML element in the layout page:

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

Save your change and refresh the page.

Notice that the browser title, the primary heading, and the secondary headings have changed.

(If you don’t see changes in the browser, you might be viewing cached content.

Press Ctrl+F5 in your browser to force the response from the server to be loaded.)

The browser title is created with ViewData["Title"] we set in the Index.cshtml view template and the additional “- Movie App” added in the layout file.

Also notice how the content in the Index.cshtml view template was merged with theViews/Shared/_Layout.cshtml view template and a single HTML response was sent to the browser.

Layout templates make it really easy to make changes that apply across all of the pages in your application. To learn more see Layout.

Our little bit of “data” (in this case the “Hello from our View Template!” message) is hard-coded, though.

The MVC application has a “V” (view) and you’ve got a “C” (controller), but no “M” (model) yet.

Shortly, we’ll walk through how 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, though, let’s first talk about passing information from the controller to a view.

Controller classes are invoked in response to an incoming URL request.

A controller class is where you write the code that handles the incoming browser requests, retrieves data from a database, and ultimately最后 decides what type of response to send back to the browser.

View templates can then be used from a controller to generate and format an HTML response to the browser.

Controllers are responsible for providing whatever data or objects are required in order for a view template to render a response to the browser.

A best practice: A view template should never perform business logic or interact with a database directly.

Instead, a view template should work only with the data that’s provided to it by the controller.

Maintaining this “separation of concerns” helps keep your code clean, testable and more maintainable.

Currently, the Welcome method in the HelloWorldController class takes a name and a ID parameter and then outputs the values directly to the browser.

Rather than have the controller render this response as a string, let’s change the controller to use a view template instead.

The view template will generate a dynamic response, which means that you need to pass appropriate bits of data from the controller to the view in order to generate the response.

You can do this by having the controller put the dynamic data (parameters) that the view template needs in a ViewData dictionary that the view template can then access.

Return to the HelloWorldController.cs file and change the Welcome method to add a Message and NumTimes value to the ViewData dictionary.

The ViewData dictionary is a dynamic object, which means you can put whatever you want in to it; the ViewData object has no defined properties until you put something inside it.

The MVC model binding system automatically maps the named parameters (name and numTimes) from the query string in the address bar to parameters in your method.

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 = )
{
ViewData["Message"] = $"Hello {name}";
ViewData["NumTimes"] = numTimes;
return View();
}
}
}

The ViewData dictionary object contains data that will be passed to the view. Next, you need a Welcome view template.

  • Right click on the Views/HelloWorld folder, and then Add > New Item.
  • In the Add New Item - MvcMovie dialog
    • In the search box in the upper-right, enter view
    • Tap MVC View Page
    • In the Name box, enter Welcome.cshtml
    • Tap Add

You’ll create a loop in the Welcome.cshtml view template that displays “Hello” NumTimes.

Replace the contents of Views/HelloWorld/Welcome.cshtml with the following:

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

Save your changes and browse to the following URL:

http://localhost:63126/HelloWorld/Welcome?name=chucklu&numTimes=2

Data is taken from the URL and passed to the controller using the MVC model binder .

The controller packages the data into a ViewData dictionary and passes that object to the view.

The view then renders the data as HTML to the browser.

In the sample above, we used the ViewData dictionary to pass data from the controller to a view.

Later in the tutorial, we will use a view model to pass data from a controller to a view.

The view model approach to passing data is generally much preferred over the ViewData dictionary approach.

See 

Adding a view的更多相关文章

  1. 007.Adding a view to an ASP.NET Core MVC app -- 【在asp.net core mvc中添加视图】

    Adding a view to an ASP.NET Core MVC app 在asp.net core mvc中添加视图 2017-3-4 7 分钟阅读时长 本文内容 1.Changing vi ...

  2. ASP.NET Core 中文文档 第二章 指南(4.3)添加 View

    原文:Adding a view 作者:Rick Anderson 翻译:魏美娟(初见) 校对:赵亮(悲梦).高嵩(Jack).娄宇(Lyrics).许登洋(Seay).姚阿勇(Dr.Yao) 本节将 ...

  3. iphone dev 入门实例1:Use Storyboards to Build Table View

    http://www.appcoda.com/use-storyboards-to-build-navigation-controller-and-table-view/ Creating Navig ...

  4. Adding Pagination 添加分页

    本文来自: http://www.bbsmvc.com/MVC3Framework/thread-206-1-1.html You can see from Figure 7-16 that all ...

  5. View Programming Guide for iOS ---- iOS 视图编程指南(四)---Views

    Views Because view objects are the main way your application interacts with the user, they have many ...

  6. iOS Programming View Controllers 视图控制器

    iOS Programming View Controllers  视图控制器  1.1  A view controller is an instance of a subclass of UIVi ...

  7. viewpaper 抽屉

    引用:http://www.apkbus.com/android-18384-1-1.html 在为ViewFlipper视图切换增加动画和Android中实现视图随手势移动中实现了视图随手势切换,现 ...

  8. 【ASP.NET MVC 5】第27章 Web API与单页应用程序

    注:<精通ASP.NET MVC 3框架>受到了出版社和广大读者的充分肯定,这让本人深感欣慰.目前该书的第4版不日即将出版,现在又已开始第5版的翻译,这里先贴出该书的最后一章译稿,仅供大家 ...

  9. 【IOS笔记】Views

    Views Because view objects are the main way your application interacts with the user, they have many ...

随机推荐

  1. PHP序列化 反序列化

    序列化是将变量转换为可保存或传输的字符串的过程:反序列化就是在适当的时候把这个字符串再转化成原来的变量使用.这两个过程结合起来,可以轻松地存储和传输数据,使程序更具维护性. 1. serialize和 ...

  2. ViewPager PagerAdapter 的使用

    1: 目的,实现全屏滑动的效果 2:类似于BaseAdapter public class MyPagerAdapter extends PagerAdapter { private Context ...

  3. android AIDL示例代码(mark下)

    1.demo结构图 2.ipcclient Book类. package com.mu.guoxw.ipcclient; import android.os.Parcel; import androi ...

  4. 酷派改变者S1(C105/C105-6/C105-8) 解锁BootLoader 并刷入recovery root

    首先下载好工具链接:https://pan.baidu.com/s/1qZjOCUw 密码:u2dr 备用下载链接:https://pan.baidu.com/s/1pMlmAef 本篇教程教你如何傻 ...

  5. 书不在多,精读则灵 - Oracle入门书籍推荐

      作者:eygle |English [转载时请标明出处和作者信息]|[恩墨学院 OCM培训传DBA成功之道]链接:http://www.eygle.com/archives/2006/08/ora ...

  6. 深圳面试一周记录——.NET(B/S)开发

    个人简单信息:2011年毕业,最高学历大专,最近一份工作在广州:有做架构设计经验,有一年的带团队(10人左右)经验:互联网和行业软件公司都待过. 为免不必要的争论,本文说地址的就不说公司行业,说公司行 ...

  7. [Advanced Algorithm] - Inventory Update

    题目 依照一个存着新进货物的二维数组,更新存着现有库存(在 arr1 中)的二维数组. 如果货物已存在则更新数量 . 如果没有对应货物则把其加入到数组中,更新最新的数量. 返回当前的库存数组,且按货物 ...

  8. .NET 解决方案 核心库整理

    一系列令人敬畏的.NET核心库,工具,框架和软件: https://www.cnblogs.com/weifeng123/p/11039345.html 企业级解决方案收录:  https://www ...

  9. BRAFT EDITOR富文本编辑器

    https://braft.margox.cn/demos/basic     官方文档 import React from 'react' import Uploading from '../Upl ...

  10. Python实现ATM+购物商城

    需求: 模拟实现一个ATM + 购物商城程序 额度 15000或自定义 实现购物商城,买东西加入 购物车,调用信用卡接口结账 可以提现,手续费5% 每月22号出账单,每月10号为还款日,过期未还,按欠 ...