View, View data, and HTML helper

Source: Internet
Author: User
Document directory
  • View
  • Create View
  • Add content to a view
  • Use HTML helper to generate View content
  • Use View data to pass data to the view

This tutorial aims to briefly introduce ASP. net mvc views, View data, and HTML helper. At the end of this tutorial, you will learn how to create a new view, how to pass data from the Controller to the view, and how to use HTML helper to generate content in the view.

View

Unlike ASP. NET or Active Server Pages, ASP. net mvc does not contain any content directly related to the page. In ASP. net mvc applications, the disk does not have a page corresponding to the path in the URL entered in the browser address bar. In ASP. net mvc applications, the content closest to the page is calledView.

In ASP. net mvc applications, browser requests are mapped to Controller operations. The Controller operation may return a view. However, controller operations may execute other types of operations, such as redirecting users to another controller.

Program list 1 contains a simple controller named homecontroller.HomecontrollerPublish two controller operations, namedIndex ()AndDetails ().

Program list 1Homecontroller. CS

Copy code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

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

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

Enter the following URL in the address bar of the browser to activate the first operation,Index ()Operation:

/Home/Index

Enter the following URL in the address bar of the browser to activate the second operation,Details ()Operation:

/Home/details

Index ()The operation returns a view. Most operations created will return to the view. However, the operation can also return other types of operation results. For example,Details ()Operation returns redirecttoactionresult, which can redirect incoming requestsIndex ()Operation.

Index ()The operation contains the following line of code:

Return view ();

This line of code returns a view of the following paths on the Web server:

\ Views \ home \ index. aspx

The view path specifies the name of the controller and the name of the controller operation.

If you want to, you can specify the view. The following code returns a view named "Fred:

Copy code

return View();

This line of code returns a view of the following paths on the Web server:

\ Views \ home \ index. aspx

The view path specifies the name of the controller and the name of the controller operation.

If you want to, you can specify the view. The following code returns a view named "Fred:

Copy code

return View(“Fred”);

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

\ Views \ home \ Fred. aspx

Create View

Right-click a folder in the Solution Explorer window, and select the menu option add, new item (1) to create a view. Select the MVC view page template to add a standard view to the project.

Figure 1: Add a new view to the project (click to view the big picture)

Note that you cannot add a view to a project just like adding a page to an ASP. NET or Active Server Pages application. You must add the view to a folder with the same controller name (without the Controller prefix. For example, if you want to create a new view named indexProductcontrollerYou must add the view to the following folder of the project:

\ Views \ product \ index. aspx

The name of the folder containing the view must correspond to the name of the controller of the returned view.

Add content to a view

A view is a standard (x) HTML document that can contain scripts. Add dynamic content to the view using scripts.

For example, the view in program list 2 shows the current date and time.

Program list 2 \ views \ home \ index. aspx

Copy code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApp.Views.Home.Index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title>Index</title>
<body>
<div>
The current date and time is:
<% Response.Write(DateTime.Now);%>
</div>
</body>

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

Copy code

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

Use the script separator <% and %> to mark the start and end of the script. This script is written in C. It callsResponse. Write ()Method to display the current date and time in the browser. The script separator <% and %> can be used to execute one or more statements.

Because it is often calledResponse. Write ()So Microsoft providesResponse. Write ()Method. The view in program listing 3 uses the separator <% = and %> as the callResponse. Write ().

Program list 3 views \ home \ index2.aspx

Copy code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index2.aspx.cs" Inherits="MvcApp.Views.Home.Index2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title>Index2</title>
<body>
<div>
The current date and time is:
<%=DateTime.Now%>
</div>
</body>

You can use any. NET language to generate dynamic content in the view. Generally, you can use Visual Basic. Net or C # To write controllers and views.

Use HTML helper to generate View content

To make it easier to add content to a view, you must useHTML helper. HTML helper is a method for generating strings. You can use HTML helper to generate standard HTML elements, such as text boxes, links, drop-down lists, and list boxes.

For example, the view in program list 4 uses two HTML helper,Textbox ()AndPassword ()Helper to generate the logon form (2 ).

Program list 4 \ views \ home \ index3.aspx

Copy code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index3.aspx.cs" Inherits="MvcApp.Views.Home.Index3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title>Login Form</title>
<body>
<div>
<form method="post" action="/Home/Login">
<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" />
</form>
</div>
</body>

Figure 2: Standard Logon form (click to view the big picture)

All HTML helper methods are called in the HTML attribute of the view. For exampleHtml. Textbox ()Method to render textbox.

Note that the delimiters <% = and %> must be used to call HTML helper. HTML helper only returns a string. Need to callResponse. Write ()To render the content in the browser.

The HTML helper method is optional. By reducing the amount of HTML and scripts to be written, HTML helper makes work easier. The view in program listing 5 presents the same content as program listing 4 without using HTML helper.

Program list 5 \ views \ home \ index4.aspx

Copy code

<%@ 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">
<title>Login Form without Help</title>
<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>

You can also create your own HTML helper. For example, you can createGridview ()Helper method. InCreate custom HTML helperThis topic is discussed in the tutorial.

Use View data to pass data to the view

You can use the viewdata attribute of a view to pass data from the Controller to the view. For example, the Controller in program listing 6 adds a message to the view data.

Program list 6Productcontroller. CS

Copy code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApp.Controllers
{
public class ProductController : Controller
{
public ActionResult Details()
{
ViewData["message"] = "Hello World!";
return View();
}
}
}

The viewdata attribute of the controller represents a set of paired names and values. In program listing 6,Details ()Method to add an item to the name "message" with the value "Hello world !" . When the view is composedDetails ()When the method is returned, the view data is automatically transmitted to the view.

The view in program listing 7 retrieves messages from the View data and presents the messages to the browser.

Program list 7 \ views \ product \ details. aspx

Copy code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Details.aspx.cs" Inherits="MvcApp.Views.Product.Details" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title>Product Details</title>
<body>
<div>
<%=Html.Encode(ViewData["message"])%>
</div>
</body>

Please note that the view usesHtml. encode ()HTML helper method.Html. encode ()HTML helper encodes special characters such as <and> into characters that can be safely displayed on the web page. Whenever the content submitted to the website is displayed, the content should be encoded to prevent javascript injection attacks.

(Because we areProductcontrollerCreates a message, so you do not need to encode the message. However, always callHtml. encode ()Is a good habit .)

In program listing 7, we use View data to transmit simple string messages from the Controller to the view. You can also use View data to transfer other types of data (such as the set of database records) from the Controller to the view. For example, if you want to display the contents of the Products Database Table in the view, you should pass the database record set in the View data.

You can also transfer strongly typed View data from the Controller to the view. InMeasure the test taker's understanding about data and views in a strongly-typed view.This topic is discussed in the tutorial.

Summary

This tutorial briefly introduces ASP. net mvc view, View data, and HTML helper. In the first part, we learned how to add a new view to the project. You know that you must add a View to the correct folder before calling it from a specific controller. Next, we will discuss HTML helper. I learned how html helper helps you easily generate standard HTML content. Finally, we learned how to use View data to transmit data from the Controller to the view.

Msdn http://msdn.microsoft.com/zh-cn/dd320348.aspx reprinted

 

Related Article

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.