`
suizhikuo
  • 浏览: 27092 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ASP.NET MVC 3 (Adding a View) (3/9)

 
阅读更多

Adding a View

In this section we're going to modify the HelloWorldController class to use a view template file to cleanly encapsulate the process of generating HTML responses to a client.

Let's start by using a view template with the Index method in the HelloWorldController class. Currently the Index method returns a string with a message that is hard-coded within the controller class. Change the Index method to return a View object, as shown in the following:

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

Let's now add a view template to our project that we can invoke with the Index method. To do this, right-click inside the Index method and click Add View.

The Add View dialog box appears. Leave the default entries and click the Add button.

The MvcMovie/Views/HelloWorld folder and the MvcMovie/Views/HelloWorld/Index.cshtml file are created. You can see them in Solution Explorer:

helloWorldVWD_Index

Add some HTML under the <h2> tag. The modified MvcMovie/Views/HelloWorld/Index.cshtml file is shown below.

@{
  ViewBag.Title = "Index";
}

<h2>Index</h2>

<b>Hello</b> World!

Run the application and browse to the "hello world" controller (http://localhost:xxxx/HelloWorld). The Index method in your controller didn't do much work; it simply ran the statement return View();, which indicated that we wanted to use a view template file to render a response to the client. Because we did not explicitly specify the name of the view template file to use, ASP.NET MVC defaulted to using the Index.cshtml view file within the /Views/HelloWorld folder. The image below shows the string hard-coded in the view.

Looks pretty good. However, notice that the browser's title bar says "Index" and the big title on the page says "My MVC Application." Let's change those.

Changing views and layout pages

First, let's change the text "My MVC Application." That text is shared and appears on every page. It actually appears in only one place in our project, even though it's on every page in our application. Go to the /Views/Shared folder in Solution Explorer and open the _Layout.cshtml file. This file is called a layout page and it's the shared "shell" that all other pages use.

_layout

Note the @RenderBody() line of code near the bottom of the file. RenderBody is a placeholder where all the pages you create show up, "wrapped" in the layout page. Change the <h1> heading from "My MVC Application" to "MVC Movie App".

 <div id="title">
    <h1>MVC Movie App</h1>
 </div>

Run the application and note it now says "MVC Movie App". Click the About link, and that page shows "MVC Movie App", too.

HomeAbout

The complete _Layout.cshtml file is shown below:

<!DOCTYPE html>
<html>
<head>
  <title>@ViewBag.Title</title>
  <link href="@Url.Content("/Content/Site.css")" rel="stylesheet" type="text/css" />
  <script src="@Url.Content("/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>

<body>
  <div class="page">

    <div id="header">
      <div id="title">
        <h1>MVC Movie App</h1>
      </div>

      <div id="logindisplay">
        @Html.Partial("_LogOnPartial")
      </div>

      <div id="menucontainer">

        <ul id="menu">
          <li>@Html.ActionLink("Home", "Index", "Home")</li>
          <li>@Html.ActionLink("About", "About", "Home")</li>
        </ul>

      </div>
    </div>

    <div id="main">
      @RenderBody()
      <div id="footer">
      </div>
    </div>
  </div>
</body>
</html>

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

Open MvcMovie/Views/HelloWorld/Index.cshtml. There are two places to make a change: first, the text that appears in the title of the browser, and then in the secondary header (the <h2> element). We'll make them slightly different so you can see which bit of code changes which part of the app.

@{
  ViewBag.Title = "Movie List";
}

<h2>My Movie List</h2>

<b>Hello</b> World!

Run the application and browse to http://localhost:xx/HelloWorld. Notice that the browser title, the primary heading, and the secondary headings have changed. It's easy to make big changes in your application with small changes to a view. (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.)

Our little bit of "data" (in this case the "Hello World!" message) is hard-coded, though. Our MVC application has V (views) and we've got C (controllers), 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. We want to pass what a view template requires in order to render an HTML response to a client. These objects are typically created and passed by a controller class to a view template, and they should contain only the data that the view template requires — and no more.

Previously with the HelloWorldController class, the Welcome action method took a name and a numTimes parameter and then output the parameter values to the browser. Rather than have the controller continue to render this response directly, let's instead put that data in a bag for the View. Controllers and Views can use a ViewBag object to hold that data. That will be passed over to a view template automatically, and used to render the HTML response using the contents of the bag as data. That way the controller is concerned with one thing and the view template with another — enabling us to maintain clean "separation of concerns" within the application.

Alternatively, we could define a custom class, then create an instance of that object on our own, fill it with data and pass it to the View. That is often called a ViewModel, because it's a custom Model for the View. For small amounts of data, however, the ViewBag works great.

Return to the HelloWorldController.cs file change the Welcome method inside the controller to put the Message and NumTimes into the ViewBag. The ViewBag is a dynamic object. That means you can put whatever you want in to it. The ViewBag has no defined properties until you put something inside it.

The complete HelloWorldController.cs with the new class in the same file.

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();
    }
  }
}

Now our ViewBag contains data that will be passed over to the View automatically. Again, alternatively we could have passed in our own object like this if we liked:

return View(myCustomObject);

Now we need a WelcomeView template! Run the application so the new code is compiled. Close the browser, right-click inside the Welcome method, and then click Add View.

Here's what your Add View dialog box looks like.

Add the following code under the <h2> element in the new Welcome.cshtml file. We'll make a loop and say "Hello" as many times as the user says we should!

@for (int i=0; i < ViewBag.NumTimes;i++) {
   <h3>@ViewBag.Message @i.ToString()</h3>
}

Run the application and browse to http://localhost:xx/HelloWorld/Welcome?name=Scott&numtimes=4. Now data is taken from the URL and passed to the controller automatically. The controller packages up the data into a ViewBag object and passes that object to the view. The view than displays the data as HTML to the user.

helloWorldScott4

Well, that was a kind of an "M" for model, but not the database kind. Let's take what we've learned and create a database of movies.

分享到:
评论

相关推荐

    node-v16.12.0-darwin-x64.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    试用Dev Containers的示例项目-Go

    计算机技术是指评价计算机系统的各种知识和技能的总称。它涵盖了计算机硬件、软件、网络和信息安全等方面。计算机技术的发展使我们能够进行高效的数据处理、信息存储和传输。现代计算机技术包括操作系统、数据库管理、编程语言、算法设计等。同时,人工智能、云计算和大数据等新兴技术也在不断推动计算机技术的进步。计算机技术的应用广泛,涵盖了各个领域,如商业、医疗、教育和娱乐等。随着计算机技术的不断革新,我们可以更加高效地实现预期自动化、标准化

    NTsky新闻发布v1.0测试版(提供JavaBean).zip

    ### 内容概要: 《NTsky新闻发布v1.0测试版》是一款基于 Java 开发的新闻发布系统的测试版本,旨在为新闻机构和媒体提供一个简单易用的新闻发布平台。该系统具有基本的新闻发布和管理功能,包括新闻分类、新闻编辑、新闻发布等核心功能。此外,该版本还提供了 JavaBean,使开发人员能够方便地将系统集成到自己的项目中,快速实现新闻发布的功能。 ### 适用人群: 本测试版本适用于新闻机构、媒体从业者以及Java开发人员。如果你是一家新闻机构或媒体,希望拥有一个简单易用的新闻发布平台,方便快捷地发布和管理新闻,那么这个测试版本将为你提供一个初步的体验。同时,如果你是一名Java开发人员,希望学习和掌握新闻发布系统的开发技术,并且对新闻行业有一定的了解,那么通过这个测试版本,你可以获取到一些JavaBean,并且可以参考系统的设计和实现,为你的项目开发提供参考和借鉴。无论是从业务需求还是技术学习的角度,该测试版本都将为你提供一定的帮助和支持。

    JavaScript介绍.zip

    javascript,JavaScript 最初由 Netscape 公司的 Brendan Eich 在 1995 年开发,用于 Netscape Navigator 浏览器。随着时间的推移,JavaScript 成为了网页开发中不可或缺的一部分,并且其应用范围已经远远超出了浏览器,成为了全栈开发的重要工具。

    15-21.php

    15-21.php

    汽车租赁系统(毕业设计)

    汽车租赁系统后端采用了spring,spring mvc,mybatis框架,前端使用了layui,界面美观。 包含功能:客户管理,车辆管理,出租,出租单管理,汽车入库,检查单管理,菜单管理,用户管理,角色管理,日志管理,统计分析等。 该毕业设计功能涵盖了大部分汽车租赁中的业务需求,特点是业务功能较多,有助于学生加深业务到技术的理解。

    设计模式_行为型_访问者模式.md

    设计模式_行为型_访问者模式

    HTML25-创意网站产品主页模板官网落地页APP主页产品宣传页源码 landing静态页面.zip

    HTML25-创意网站产品主页模板官网落地页APP主页产品宣传页源码 landing静态页面

    快手弹幕采集学习源码!!

    快手弹幕采集学习源码

    general-exporter windows

    自定义监控项 Windows 二进制文件

    数据可视化大屏展示系统HTML模板源码 大数据大屏展示源码 VUE.zip

    数据可视化大屏展示系统HTML模板源码 大数据大屏展示源码 VUE

    node-v18.2.0-linux-armv7l.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    这个项目是用于个人参加浙江大学移动创新竞赛而使用。.zip

    这个项目是用于个人参加浙江大学移动创新竞赛而使用。

    2023年全国职业院校技能大赛“区块链技术应用赛项”国赛正式赛题

    2023年全国职业院校技能大赛“区块链技术应用赛项”国赛正式赛题 高职 全国职业院校技能大赛 正式赛题

    基于stm32的智能家居系统

    基于stm32的智能家居系统 基于stm32的智能家居系统

    21九章空间解析几何.pdf

    21九章空间解析几何.pdf

    吴恩达机器学习python版本代码(完结).zip

    吴恩达机器学习python版本代码(完结)

    HTML21-印刷模板官网落地页APP主页产品宣传页源码 landing静态页面.zip

    HTML21-印刷模板官网落地页APP主页产品宣传页源码 landing静态页面

    信息办公简易java开源订销管理系统-javainfo.zip

    ### 内容概要: 《[信息办公]简易Java开源订销管理系统》是一款基于 Java 开发的开源项目,旨在为企业和机构提供一套简单易用的订购和销售管理解决方案。该系统具有简洁的界面设计和丰富的功能模块,包括客户管理、产品管理、订单管理、库存管理等核心功能,同时支持生成报表和统计分析,帮助用户快速了解企业的订购和销售情况,提高管理效率和业务决策能力。 ### 适用人群: 本项目适用于企业信息办公人员和Java开发人员。如果你是一位信息办公人员,希望通过一个简单易用的系统来管理企业的订购和销售业务,该系统将为你提供一个方便快捷的解决方案。同时,如果你是一名Java开发人员,希望学习和掌握Java开发技术,并且对企业信息管理系统感兴趣,那么这个开源项目将为你提供一个学习和实践的机会。无论是从业务管理还是技术学习的角度,该项目都将为你提供实用的功能和丰富的学习资源。

    [精品] todo_appAdobeXD源码下载设计素材UI设计.xd

    [精品] todo_appAdobeXD源码下载设计素材UI设计

Global site tag (gtag.js) - Google Analytics