在添加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. Oracle 中文排序

        按照拼音顺序(常用)     ORDER BY nlssort(NAME, 'NLS_SORT=SCHINESE_PINYIN_M') 按照部首顺序 ORDER BY nlssort(NAME ...

  2. P1401 城市(30分,正解网络流)

    题目描述 N(2<=n<=200)个城市,M(1<=m<=40000)条无向边,你要找T(1<=T<=200)条从城市1到城市N的路,使得最长的边的长度最小,边不能 ...

  3. poj1328 Radar Installation 区间贪心

    题目大意: 在X轴选择尽量少的点作为圆心,作半径为d的圆.使得这些圆能覆盖所有的点. 思路: 把每个点都转化到X轴上.也就是可以覆盖这个点的圆心的位置的范围[a,b].然后按照每个点对应的a从小到大排 ...

  4. js 图片轮播代码编辑

    图片轮播,将几张图片统一放在展示平台 banner上,通过banner移动将图片轮流播放. <script>// 取对象 var btn_l = document.getElementsB ...

  5. 【Linux】Ubuntu输入法不能开机自启的解决方法

    操作系统:Ubuntu Kylin 16.10 自从操作系统安装了搜狗输入法以后,每次重启电脑都需要手动启动Fcitx,才能启动搜狗输入法.下面给大家介绍输入法开机自启的解决方法: 操作系统的用户家目 ...

  6. dubbo介绍及实战

    1. dubbo是什么? Dubbo是一个分布式服务框架,致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案.其核心部分包含: 远程通讯: 提供对多种基于长连接的NIO框架抽象封 ...

  7. 07--c++类的构造函数详解

    c++类的构造函数详解 c++构造函数的知识在各种c++教材上已有介绍,不过初学者往往不太注意观察和总结其中各种构造函数的特点和用法,故在此我根据自己的c++编程经验总结了一下c++中各种构造函数的特 ...

  8. (转)基于Metronic的Bootstrap开发框架经验总结(7)--数据的导入、导出及附件的查看处理

    http://www.cnblogs.com/wuhuacong/p/4777720.html 在很多系统模块里面,我们可能都需要进行一定的数据交换处理,也就是数据的导入或者导出操作,这样的批量处理能 ...

  9. (转)Arcgis for JS实现台风运动路径与影像范围的显示

    http://blog.csdn.net/gisshixisheng/article/details/42025435 首先,看看具体的效果: 初始化状态 绘制中 绘制完成 首先,组织数据.我组织的数 ...

  10. Laravel -- windows apache .htaccess https 路由重写

    一: <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{SERVER_PORT} !^443 RewriteCond %{RE ...