理解视图

ASP.NET MVC View Overview (C#)

The purpose of this tutorial is to provide you with a brief introduction to ASP.NET MVC views, view data, and HTML Helpers. By the end of this tutorial, you should understand how to create new views, pass data from acontroller to a view, and use HTML Helpers to generate content in a view.

  这篇教程的目的是为你简单的介绍 ASP.NET MVC views, view data, and HTML Helpers。通过这篇文章,你将理如何去创建视图,如何将数据从controller传送到view,还有怎样使用HTML Helpers去生成View中内容。

Understanding Views

For ASP.NET or Active Server Pages, ASP.NET MVC does not include anything that directly corresponds to a page. In an ASP.NET MVC application, there is not a page on disk that corresponds to the path in the URL that you type into the address bar of your browser. The closest thing to a page in an ASP.NET MVC application is something called a view.ASP.NET MVC application, incoming browser requests are mapped to controller actions. A controller action might return a view. However, a controller action might perform some other type of action such as redirecting you to another controller action.

  与ASP.NET、ASP不同,ASP.NET MVC并没有包括任何直接对应的页面。在ASP.NET MVC应用程序中,磁盘中没有一个与你在浏览器中输入的URL地址对应的页面。最接近页面的东西叫做View(视图)。

  在ASP.NET MVC应用程序中,传入的浏览器请求映射到控制器动作。一个控制器的动作将返回一个View。当然,一个控制器的动作也可能会执行类型的 动作,比如重定向到另外一个控制器的动作。

Listing 1 contains a simple controller named the HomeController. The HomeController exposes two controller actions named Index() and Details().

  代码清单1含有一个简单的控制器,叫做HomeController。HomeController公开了两个控制器动作,叫做Index()和Details()。

Listing 1 – HomeController.cs

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Details()
        {
            return RedirectToAction("Index");
        }
    }
}

 

You can invoke the first action, the Index() action, by typing the following URL into your browser address bar:

/Home/Index

You can invoke the second action, the Details() action, by typing this address into your browser:

/Home/Details

  你可以通过在浏览器中输入下面的地址去调用第一个动作Index():/Home/Index

  你可以通过在浏览器中输入下面的地址去调用第二个动作Index():/Home/Details

The Index() action returns a view. Most actions that you create will return views. However, an action can return other types of action results. For example, the Details() action returns a RedirectToActionResult that redirects incoming request to the Index() action.

  Index()动作返回一个View.你所创建的大部分的动作将返回Views,然而,一个动作也可以返回其他类型的响应结果。例如,Detail()动作返回的是一个传入到Index()动作的RedirectToActionResult 。

The Index() action contains the following single line of code:

View();

This line of code returns a view that must be located at the following path on your web server:

\Views\Home\Index.aspx

  Index()动作包含了下面一行代码:

  View();

  这一行代码返回一个View,这个View在你的服务器上必须放在下面的路径:

  \Views\Home\Index.aspx

 

The path to the view is inferred from the name of the controller and the name of the controller action.

If you prefer, you can be explicit about the view. The following line of code returns a view named “Fred”:

View(“Fred”);

When this line of code is executed, a view is returned from the following path:

\Views\Home\Fred.aspx

If you plan to create unit tests for your ASP.NET MVC application then it is a good idea to be explicit about view names. That way, you can create a unit test to verify that the expected view was returned by a controller action.

      View的路径可以通过Controller的名字和Controller的动作推断出来,如果你愿意,你可以显示的指定View,下面一行代码返回一个名字为“Fred”的View:

      View("Fred");

      当这行代码被执行,将会从下面的的路径返回一个View:

     \Views\Home\Fred.aspx

     如果你打算为你的ASP.NET MVC 应用程序创建单元测试,那么,显示指定View的名字是一个很好的主意。那样你可以通过创建单元测试去验证Controller的动作返回的View是否是你所期望的。

Adding Content to a View

A view is a standard (X)HTML document that can contain scripts. You use scripts to add dynamic content to a view.For example, the view in Listing 2 displays the current date and time.

      View是一个可以包含脚本的标准的(X)HTML的文本,你可以使用脚本为View添加动态的内容。例如,代码清单2的View显示当前的日期和时间。

 

Listing 2 – \Views\Home\Index.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Index</title> </head> <body> <div> The current date and time is <% Response.Write(DateTime.Now);%> </div> </body> </html>

Notice that the body of the HTML page in Listing 2 contains the following script:

<% Response.Write(DateTime.Now);%>

You use the script delimiters <% and %> to mark the beginning and end of a script. This script is written in C#. It displays the current date and time by calling the Response.Write() method to render content to the browser. The script delimiters <% and %> can be used to execute one or more statements.

Since you call Response.Write() so often, Microsoft provides you with a shortcut for calling the Response.Write() method. The view in Listing 3 uses the delimiters <%= and %> as a shortcut for

calling Response.Write().

  注意到代码清单2中的HTML页面的body中含有下面的脚本:

  你可以使用脚本分隔符<%和%>来标记脚本的开始和结束。这个脚本是使用C#编写的。通过调用Response.Write()方法将当前的日期和时间呈现到了浏览器中。脚本分隔符<%和%>可以用于执行一条或者多条语句。因为会经常调用Response.Write()方法,Microsoft为你提供了一种调用Response.Write()的快捷方式。代码清单3中的View使用<%=和%>作为调用Response.Write()方法的简单途径。

Listing 3 – Views\Home\Index2.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Index</title> </head> <body> <div> The current date and time is <%=DateTime.Now %> </div> </body> </html>

You can use any .NET language to generate dynamic content in a view. Normally, you'll use either Visual Basic .NET or C# to write your controllers and views.

  你可以使用任何.NET语言去生成View中的动态内容,通常,你既可以使用Visual Basic .NET也可以使用C#去写你的Controllers和Views。

Using HTML Helpers to Generate View Content

To make it easier to add content to a view, you can take advantage of something called an HTML Helper.

An HTML Helper, typically, is a method that generates a string. You can use HTML Helpers to generate standard HTML elements such as textboxes, links, dropdown lists, and list boxes.

For example, the view in Listing 4 takes advantage of three HTML Helpers -- the BeginForm(), the

TextBox() and Password() helpers -- to generate a Login form (see Figure 1).

  为了更简单的往View中添加内容,您可以利用HTML Helper。HTML Helper,通常是一个生成字符串的方法。你可以使用HTML Helpers来生成标准的HTML元素,例如文本框、链接、下拉框和列表框。

  例如,代码清单4中的View利用了三个HTML Helpers,BeginForm(),TextBox()和Password(),用于生成一个登录窗体(见图1)。

 

Listing 4 -- \Views\Home\Login.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Login Form</title> </head> <body> <div> <% using (Html.BeginForm()) { %> <label for="UserName">User Name:</label> <br /> <%= Html.TextBox("UserName") %> <br /><br /> <label for="Password">Password:</label> <br /> <%= Html.Password("Password") %> <br /><br /> <input type="submit" value="Log in" /> <% } %> </div> </body> </html>

Figure 01: A standard Login form (Click to view full-size image)

 

All of the HTML Helpers methods are called on the Html property of the view. For example, you render a TextBox by calling the Html.TextBox() method.

Notice that you use the script delimiters <%= and %> when calling both the Html.TextBox() and Html.Password() helpers. These helpers simply return a string. You need to call Response.Write() in

order to render the string to the browser.

Using HTML Helper methods is optional. They make your life easier by reducing the amount of HTML and script that you need to write. The view in Listing 5 renders the exact same form as the view in Listing 4 without using HTML Helpers.

  所有的HTML Helpers方法都在View的Html属性上调用。例如,你可以通过调用Html.TextBox()方法来呈现一个文本框。注意,当你在调用Html.TextBox()和Html.Password() 辅助方法时,必须使用脚本分隔符<%=和%>。这些辅助法仅仅是返回一个字符串。你需要调用Response.Write()来将字符串呈现到浏览器中。

  使用HTML Helper方法是可选的。它们通过减少你需要编写的HTML和Script数量使得开发更为简单。代码清单5中的View呈现了与代码清单4中完全相同的窗体,但是没有使用HTML Helpers。

Listing 5 -- \Views\Home\Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index4.aspx.cs" 
Inherits="MvcApp.Views.Home.Index4" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Login Form without Help</title> </head> <body> <div> <form method="post" action="/Home/Login"> <label for="userName">User Name:</label> <br /> <input name="userName" /> <br /><br /> <label for="password">Password:</label> <br /> <input name="password" type="password" /> <br /><br /> <input type="submit" value="Log In" /> </form> </div> </body> </html>

You also have the option of creating your own HTML Helpers. For example, you can create a GridView()

helper method that displays a set of database records in an HTML table automatically. We explore this

topic in the tutorial Creating Custom HTML Helpers.

  你也可以选择创建你自己的HTML Helpers,例如,你可以创建的一个GridView()的辅助方法,自动地在一个HTML表格中显示一系列的数据库记录。我们将在创建自定义的HTML Helpers的教程中来讨论这个话题。

Using View Data to Pass Data to a View

You use view data to pass data from a controller to a view. Think of view data like a package that you

send through the mail. All data passed from a controller to a view must be sent using this package.

For example, the controller in Listing 6 adds a message to view data.

  你可以使用ViewData来从Controller传送数据到View。将ViewData想象成为你发送邮件的一个包。所有的通过Controller传送到View中数据必须使用这个包。例如,代码清单6中的Controller往ViewData添加了一条消息。

Listing 6 – ProductController.cs

using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class ProductController : Controller
{
public ActionResult Index()
{
ViewData["message"] = "Hello World!";
return View();
}
}
}

The controller ViewData property represents a collection of name and value pairs. In Listing 6, the Index() method adds an item to the view data collection named message with the value “Hello World!”. When the

view is returned by the Index() method, the view data is passed to the view automatically.

The view in Listing 7 retrieves the message from the view data and renders the message to the browser.

  Controller的ViewData属性代表着一个名称/值对的集合。在代码清单6中,Index()方法向ViewData集合中添加了一个名为message的项值为“Hello World!”。当视图由Index()方法返回时,ViewData将会自动传递给视图。代码清单7中的视图从ViewData中获取了消息,并且将消息呈现到了浏览器中。

Listing 7 -- \Views\Product\Index.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Product Index</title> </head> <body> <div> <%= Html.Encode(ViewData["message"]) %> </div> </body> </html>

Notice that the view takes advantage of the Html.Encode() HTML Helper method when rendering the message. The Html.Encode() HTML Helper encodes special characters such as < and > into characters

that are safe to display in a web page. Whenever you render content that a user submits to a website,

you should encode the content to prevent JavaScript injection attacks.

(Because we created the message ourselves in the ProductController, we don’t really need to encode

the message. However, it is a good habit to always call the Html.Encode() method when displaying

content retrieved from view data within a view.)

In Listing 7, we took advantage of view data to pass a simple string message from a controller to a view.

You also can use view data to pass other types of data, such as a collection of database records, from a controller to a view. For example, if you want to display the contents of the Products database table in a view, then you would pass the collection of database records in view data.

You also have the option of passing strongly typed view data from a controller to a view. We explore this topic in the tutorial Understanding Strongly Typed View Data and Views.

  注意到当呈现消息时,视图利用了Html.Encode() Helper方法。这个方法将如“<”和“>”这样的特殊字符编码为在web页面中能够安全显示的字符。无论何时呈现用户提交到网站的内容时,你都应该对内容进行编码,以避免JavaScript入攻击。

(因为我们自己在ProductController中创建了消息,所以并不是真的需要对消息进行编码。然而,当在视图中显示获取自ViewData中的内容时,总是调用Html.Encode()是一个很好的习惯。)

在代码清单7中,我们利用了ViewData来将一个简单的字符串消息从Controller传送到了View。你也可以使用ViewData将其他类型的数据,如一个数据库记录集合,从控制器传递到视图,例如,如果你想要在视图中显示Products数据库表的内容,那么你可以将数据库记录的集合保存在ViewData中进行传递。

你也可以从控制器向视图传递强类型ViewData。我们将在教程“理解强类型View Data和视图”中讨论这个话题。

Summary

This tutorial provided a brief introduction to ASP.NET MVC views, view data, and HTML Helpers. In the first section, you learned how to add new views to your project. You learned that you must add a view to the right folder in order to call it from a particular controller. Next, we discussed the topic of HTML Helpers. You learned how HTML Helpers enable you to easily generate standard HTML content. Finally, you learned how

to take advantage of view data to pass data from a controller to a view.

  这篇教程提供了对ASP.NET MVC,View,ViewData 和 HTML Helpers的一个简短的介绍。在第一部分,你学习了如何向项目中添加新的视图。你学习了必须将视图添加到正确的文件夹中,以使它能够被特定的控制器调用。接下来,我们讨论了HTML Helpers这一主题。你学习了如何使用HTML Helpers轻松地生成标准的HTML内容。最后,你学习了如何利ViewData将数据从控制器传递给视图 。

 

posted @ 2009-12-14 17:28  supperwu  阅读(400)  评论(0编辑  收藏  举报