Original article:Http://www.asp.net/learn/mvc/tutorial-04-cs.aspx
This tutorial provides a brief introduction to ASP. net mvc views, View data, and HTML helpers. After reading this article, you should be able to understand how to create a new view, pass data from the Controller to the view, and use HTML helper to generate content in the view.
1. Understand the view
Unlike ASP. NET or ASP, ASP. NET does not directly correspond to a page. Application in ASP. NET MVCProgram, There is no page on the disk to correspond to the URL path you entered in the browser address bar. In ASP. net mvc applications, what is closest to the page is calledView(View.
In ASP. net mvc applications, browser requests that are about to arrive are mapped to Controller actions. A controller action may return a view. However, a controller action may execute some type of action, such as redirecting you to another controller action.
CodeListing 1 contains a simple Controller called homecontroller. Homecontroller exposes Two Controller actions, called index () and details ().
Code List 1-homecontroller. CS
using system;
using system. collections. generic;
using system. LINQ;
using system. web;
using system. web. MVC;
namespace mvcapp. controllers
{< br> [handleerror]
Public class homecontroller : controller
{< br> Public actionresult index ()
{< br> return View ();
}
PublicActionresult details ()
{
ReturnRedirecttoaction ("Index");
}
}
}
You can enter the following URL in the address bar of the browser to call the first action, index () action:
/Home/Index
You can enter this address in the browser to call the second action, details () action:
/Home/details
The index () action returns a view. Most of the actions you create will return a view. However, actions can return any type of action results. For example, the details () action returns a redirecttoactionresult, which can redirect the incoming request to the index () action.
The index () action contains the following code:
ReturnView ();
This line of code returns a view. The path of this view on the server must be the same as the following path:
"Views" home "index. aspx
The view path is inferred from the Controller and controller action names.
If you want to, you can explicitly specify the view. The following code returns a view named "Fred ":
ReturnView ("Fred");
When this line of code is executed, a view is returned from the following path:
"Views" home "Fred. aspx
2. Create a view
You can right-click the folder in the solution browser, and select the menu items "add (ADD)" and "new item (new item)" (1 ). Select the "MVC view page" template to add the standard view to your project.
Figure 1-Add a new view to the Project
You should be aware that you cannot add a View to the project as you would in ASP. NET or ASP applications. You must add the view to the folder, and the folder name is the same as the controller name (excluding the Controller suffix ). For example, if you want to create a new view named index, which can be returned by the Controller named productcontroller, you must add this 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 that returns the view.
3. add content to the view
A view is a standard (x) HTML document that can contain scripts. You can use a script to add dynamic content to the view.
For example, the view in code list 2 shows the current date and time.
Code List 2-"views" home "index. aspx
<% @ page Language = "C #" autoeventwireup = "true" codebehind = "index. aspx. CS "inherits =" mvcapp. views. home. index "%>
index
the current date and time is:
<% response. write (datetime. now); %>
Note that the body of the HTML page in code list 2 contains the following script:
<% 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 displays the current date and time. The content is displayed in the browser by calling the response. Write () method. The script separator <% and %> can be used to execute one or more statements.
Because the response. Write () method is often called, Microsoft provides you with a simple way to call response. Write. The view in code listing 3 uses <% = and %> as a simple way to call the response. Write () method.
Code List 3-views "home" index2.aspx
<% @ page Language = "C #" autoeventwireup = "true" codebehind = "index2.aspx. CS "inherits =" mvcapp. views. home. index2 "%>
index2
the current date and time is:
<% = datetime. now %>
You can use any. NET language to generate dynamic content in the view. You can use Visual Basic. Net or C # To compile your controller and view.
4. Use HTML helpers to generate View content
To make it easier to add content to a view, you can useHTML helper. HTML helper is a method for generating strings. You can use HTML helpers to generate standard HTML elements, such as text boxes, links, drop-down boxes, and list boxes.
For example, the view in code list 4 uses two HTML helpers, Textbox (), and password () to generate a logon form (see figure 2 ).
Code list 4-"views" home "index3.aspx
<% @ 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">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> login form </title>
</Head>
<Body>
<Div>
<Form method = "Post" Action = "/home/login">
<Label for = "username"> User name: </label>
<Br/>
<% = Html. Textbox ("username") %>
<Br/>
<Label for = "password"> password: </label>
<Br/>
<% = Html. Password ("password") %>
<Br/>
<Input type = "Submit" value = "log in"/>
</Form>
</Div>
</Body>
</Html>
Figure 2-a standard Logon form
All HTML helpers methods are called on the HTML attributes of the view. For example, you can call the HTML. Textbox () method to render a text box.
Note: When calling HTML helper, you must use the script separator <% = and %>. HTML helper only returns a string. You need to call response. Write () to render the string to the browser.
The HTML helper method is optional. They simplify development by reducing the number of HTML and scripts you write. The view in code list 5 shows the same form as in code list 4, but does not use HTML helpers.
Code List 5-"views" home "index4.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 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/>
<Label for = "password"> password: </label>
<Br/>
<Input name = "password" type = "password"/>
<Br/>
<Input type = "Submit" value = "log in"/>
</Form>
</Div>
</Body>
</Html>
You can also create your own HTML helpers. For example, you can create a gridview () helper method that automatically displays a series of database records in an HTML table. We willCreate custom HTML helpersThis topic is discussed in this tutorial.
5. Use the viewdata attribute to pass data to the view
You can use another viewdata attribute of the view to pass data from the Controller to the view. For example, the Controller in code listing 6 adds a message to viewdata.
Code List 6-productcontroller. CS
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! ";
ReturnView ();
}
}
}
The viewdata attribute of the controller represents a set of name/value pairs. In code listing 6, the details () method adds an item named message to the viewdata set with the value "Hello World !". When a view is returned by the details () method, viewdata is automatically transmitted to the view.
The view in code listing 7 obtains the message from viewdata and presents the message to the browser.
Code listing 7-"views" product "details. aspx
<% @ page Language = "C #" autoeventwireup = "true" codebehind = "details. aspx. CS "inherits =" mvcapp. views. product. details "%>
product details
<% = html. encode (viewdata ["message"]) %>
Note that when a message is displayed, the view uses the HTML. encode () helper method. The HTML. encode () HTML helper method encodes special characters such as "<" and ">" into characters that can be safely displayed on Web pages. Whenever the content submitted to the website is displayed, you should encode the content to avoid javascript injection attacks.
(Because we have created a message in productcontroller, we do not need to encode the message. However, it is a good habit to always call HTML. encode () when the content obtained from viewdata is displayed in the view .)
In code listing 7, viewdata is used to pass a simple string message from the Controller to the view. You can also use viewdata to transmit other types of data from the Controller to the view, such as a database record set. For example, if you want to display the contents of the Products Database Table in the view, you can save the set of database records in viewdata for transmission.
You can also pass strong view data to the view from the Controller. We will discuss this topic in "Understanding strong-type view data and views" in the tutorial.
6. Summary
This tutorial provides a brief introduction to ASP. net mvc views, View data, and HTML helpers. In the first part, you learned how to add a new view to the project. After learning, you must add the view to the correct folder so that it can be called by a specific controller. Next, we will discuss the theme of HTML helpers. You learned how html helpers can easily generate standard HTML content. Finally, you learned how to use viewdata to pass data from the Controller to the view.