ASP. net mvc view Overview (C #)

Source: Internet
Author: User

This tutorial introduces ASP. net mvc views, View data, and HTML helpers. At the end of the tutorial, you should understand how to create a new view, transfer data from the Controller to the view, and use the use HTML helpers to generate content in the view.

Understanding View

Unlike ASP. NET or ASP, ASP. net mvc does not include anything that directly corresponds to a page. In ASP. net mvc applications, there is no page on the hard disk that corresponds to the URL in the address bar of your browser. In ASP. net mvc applications, what is closest to a page is calledView.

ASP. net mvc application, the browser request passed in is mapped to the Controller actions. The Controller action may return a view. However, the Controller may execute other types of actions, such as redirecting you to another controller action.

Code 1 contains a simple controller named homecontroller. Homecontroller exposes two controllers, actions named index () and details ().

Code 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 enter the following URL in the address bar of your browser to call the first action, index () action:

/Home/Index

You can enter this in the address bar of your browser to call the second action, details () action:

/Home/details

Index () action returns a view. Most of the actions you create are returned to the view. However, an action can return other types of action results. For example, details () action returns a redirecttoactionresult, which redirects the incoming request to index () action.

Index () action only has a simple line of code:

View ();

This line of code returns a view that must be located in the following path of your Web server:

/Views/home/index. aspx

The view of this path is inferred by the Controller name and the Controller action name.

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

View ("Fred ");

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

/Views/home/Fred. aspx

If you want to create a unit test for your ASP. net mvc program, it is a good idea to explicitly specify the view name. In this way, you can create a unit test to verify whether the expected view is returned by a controller action.

Add content to a view

A view is a standard (x) HTML document that can contain scripts. Use scripts to add dynamic content to a view.

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

Code 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"><ptml xmlns="http://www.w3.org/1999/xhtml" ><pead id="Head1" runat="server">    <title>Index</title></pead><body>    <div>                The current date and time is    <% Response.Write(DateTime.Now);%>        </div></body></ptml>

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

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

Use the script qualifier <% and %> to indicate the start and end of the script. This script is written in C. Call the response. Write () method to display the current date and time in the browser. The script qualifier <% and %> can be used to execute one or more statements.

Since response. Write () is used so frequently, Microsoft provides a shortcut to call the response. Write () method. The view in code 3 uses the qualifier <% = and %> as the shortcut for calling response. Write.

Code 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"><ptml xmlns="http://www.w3.org/1999/xhtml" ><pead id="Head1" runat="server">    <title>Index</title></pead><body>    <div>                The current date and time is    <%=DateTime.Now %>        </div></body></ptml>

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

Use HTML helpers to generate View content

To add content to a view more simply, you can useHTML helper. HTML helper is usually a method for generating strings. You can use HTML helper to generate standard HTML elements such as input boxes, hyperlinks, drop-down boxes, and list boxes.

For example, the view in code 4 uses three HTML Helper -- beginform (), Textbox (), and password () helper -- to generate a logon form (see figure 1 ).

Code 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"><ptml xmlns="http://www.w3.org/1999/xhtml" ><pead id="Head1" runat="server">    <title>Login Form</title></pead><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></ptml>

Figure 01: A standard Logon form (click to view the full size)

All HTML helper methods are called by the HTML attribute of the view. For example, you can call the HTML. Textbox () method to render a textbox.

Note that when you call HTML. Textbox () and HTML. Password () helper, you must use the script delimiters <% = and %>. These helper returns only one string. You need to call response. Write () to render the string to the browser.

The HTML helper method is optional. They make your life easier, because they reduce the number of HTML and scripts you need to write. The view in code 5 presents the same form as in code 4, but does not use HTML helper.

Code 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"><ptml xmlns="http://www.w3.org/1999/xhtml" ><pead id="Head1" runat="server">    <title>Login Form without Help</title></pead><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></ptml>

You can also create your own HTML helper. For example, you can create a gridview () helper method to automatically display a set of database records in an HTML table. I will go to the tutorialCreate custom HTML helpersTo discuss this topic.

Transmit data to a view using View data

Use View data to transfer data from the Controller to the view. Think of View data as a package sent by mail. All data transmitted from the Controller to the view must be sent using this package. For example, the Controller in code 6 adds an information to the view data.

Code 6-productcontroller. CS

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

The viewdata attribute of the controller represents a set of key-value pairs. In code 6, the index () method adds an item named message to the view data set with the value "Hello World !". When a view is returned by the index () method, the view data is automatically transmitted to the view.

The view in code 7 retrieves the message from the View data and presents the message to the browser.

Code 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"><ptml xmlns="http://www.w3.org/1999/xhtml" ><pead id="Head1" runat="server">    <title>Product Index</title></pead><body>    <div>        <%= Html.Encode(ViewData["message"]) %>        </div></body></ptml>

Note that when the message is displayed, the view uses the HTML helper method. Html. encode () encodes special characters such as <and> into characters that can be safely displayed on the webpage. When you want to present the content submitted to the website by the user, you should encode the content to prevent javascript injection attacks.

(Because we have created information in productcontroller, we do not need to encode the information. However, it is a good habit to call the HTML. encode () method when obtaining the display content from the View data .)

In code 7, we use View data to transmit a simple string information from the Controller to the view. You can also use View data to transmit other types of data, such as a set of database records from the Controller to the view. For example, if you want to display the content in the products database table in the view, you can pass this database record set in the View data.

You can also transmit strong view data from the Controller to the view. We willUnderstanding data and views in a strongly typed ViewThis topic is discussed in the tutorial.

Summary

This tutorial provides an overview of ASP. net mvc views, View data, and HTML helper. In section 1, you learned how to add a new view to your project. You learned that you must add a view under the correct folder to call the view from a specific controller. Next, we will discuss the topic of HTML helper. You learned how html helper allows you to easily generate standard HTML content. Finally, you learned how to use View data to transmit data from the Controller to the view.

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.