ASP. net mvc view (create custom HTML helpers)-Part.2

Source: Internet
Author: User

Source: http://www.cnblogs.com/JimmyZhang/archive/2009/02/08/1371819.html Zhang Ziyang

Original article:Http://www.asp.net/learn/mvc/tutorial-04-cs.aspx

 

1. Create a custom HTML helper

The purpose of this tutorial is to demonstrate how to create custom HTML helper. You can use them in the MVC view. By using HTML helpers, you can reduce the input of a large number of HTML tags. You must enter these tags to create standard HTML pages.

In the first part of this tutorial, I described some existing HTML helper contained in ASP. NET MVC. Next, I described two methods for creating custom HTML helpers: I revealed how to create custom HTML helpers by creating static methods and extension methods.

2. understand HTML helpers

HTML helper is just a method for returning strings. This string can represent any type you want. For example, you can use HTML helper to present standard HTML tags, such as HTML <input> and tags. You can also use HTML helpers to present more complex content, such as an HTML table of a tab or database data.

The ASP. net mvc Framework contains the following standard HTML helpers set (no full column here ):

    • Html. actionlink ()
    • Html. beginform ()
    • Html. checkbox ()
    • Html. dropdownlist ()
    • Html. endform ()
    • Html. Hidden ()
    • Html. ListBox ()
    • Html. Password ()
    • Html. radiobutton ()
    • Html. textarea ()
    • Html. Textbox ()

For example, considerCodeThe form in Listing 1. This form is completed with the help of two standard HTML helpers. This form uses the HTML. beginform () and HTML. Textbox () helper methods to render a simple HTML form.

Figure 1: Page rendered using HTML helpers

Code List 1-viewshomeindex. aspx

<% @ Page Language = "C #" autoeventwireup = "true" codebehind = "index. aspx. cs" inherits = "mvcapplication1.views. Home. Index" %> <! 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>

<% Using (html. beginform ())

{%>

<Label for = "firstname"> First name: </label>

<Br/>

<% = Html. Textbox ("firstname") %>

<Br/>

<Label for = "lastname"> last name: </label>

<Br/>

<% = Html. Textbox ("lastname") %>

<Br/>

<Input type = "Submit" value = "register"/>

<% }%>

</Div>

</Body>

</Html>

The HTML. beginform () helper method is used to create the open and closed tags of HTML <form>. Note that the HTML. beginform () method is called in a using statement. The Using statement ensures that the <form> flag is disabled at the end of the using block.

If you like, you can not create using blocks. You can call the HTML. endform () helper method to close the <form> tag. Use the best way for you to create the <form> open and closed tags.

The HTML. Textbox () helper method is used to display the HTML <input> tag in code listing 1. If you select "View Source File" in your browser, you will see the htmlSource code. Note that the source code contains standard HTML tags.

Note:Note: HTML. Textbox (), HTML helper is rendered using the <% =%> label instead of the <%> label. If you do not include this equal sign, nothing will be presented to the browser.

The ASP. net mvc Framework contains few helpers methods. More likely, you need to use custom HTML helpers to extend the MVC framework. In the remaining part of this tutorial, you will learn two methods for creating custom HTML helpers.

Code List 2-index. aspx source code

<% @ Page Language = "C #" autoeventwireup = "false" codebehind = "index. aspx. cs" inherits = "mvcapplication1.index" %> <! 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>

<Title> index </title>

</Head>

<Body>

<Div>

<Form action = "http: // localhost: 33102/" method = "Post">

<Label for = "firstname"> First name: </label>

<Br/>

<Input id = "firstname" name = "firstname" type = "text" value = ""/>

<Br/>

<Label for = "lastname"> last name: </label>

<Br/>

<Input id = "lastname" name = "lastname" type = "text" value = ""/>

<Br/>

<Input id = "btnregister" name = "btnregister" type = "Submit" value = "register"/>

</Form>

</Div>

</Body>

</Html>

3. Use static methods to Create HTML helpers

The simplest way to create a new HTML helper is to create a static method that returns a string. For example, if you decide to create an HTML helper, it presents an HTML <label> tag. You can use the class in code listing 3 to present a <label>.

Code List 3-helperslabelhelper. CS

UsingSystem;

NamespaceMvcapplication1.helpers

{

Public Class Labelhelper{

Public Static StringLabel (StringTarget,StringText ){

Return String. Format ("<LabelFor= '{0}'> {1} </label>", Target, text );

}

}

}

There is nothing to say about the classes in code list 2. The label () method returns a string.

In code list 4, the modified index view uses labelhelper to present HTML <label> labels. Note that the view contains a <% @ imports %> command, which imports the application1.helpers namespace.

Code list 4-viewshomeindex2.aspx

<% @ Page Language = "C #" autoeventwireup = "true" codebehind = "index2.aspx. CS "inherits =" mvcapplication1.views. home. index2 "%> <% @ import namespace =" mvcapplication1.helpers "%> <! 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> index2 </title>

</Head>

<Body>

<Div>

<% Using (html. beginform ())

{%>

<% = Labelhelper. Label ("firstname", "First name:") %>

<Br/>

<% = Html. Textbox ("firstname") %>

<Br/>

<% = Labelhelper. Label ("lastname", "Last Name:") %>

<Br/>

<% = Html. Textbox ("lastname") %>

<Br/>

<Input type = "Submit" value = "register"/>

<% }%>

</Div>

</Body>

</Html>

4. Create HTML helpers using extension methods

If you want to create an HTML helpers, as if it is included in the ASP. net mvc framework, you need to create an extension method. The extension method allows you to add new methods for existing classes. When creating an HTML helper method, you add a new method for the htmlhelper class, which is represented by the HTML attribute of the view.

The class in code list 5 adds an extension method called label () to the htmlhelper class. There are several notes for this class. First, we noticed that this class is a static class. You must define the Extension Method in the static class.

Note that the first parameter of the label () method is preceded by the keyword "this. The first parameter of the extension method describes the class extended by this extension method.

Code List 5-helperslabelextensions. CS

UsingSystem;

UsingSystem. Web. MVC;
NamespaceMvcapplication1.helpers

{

Public Static Class Labelextensions{

Public Static StringLabel (ThisHtmlhelper helper,StringTarget,StringText ){

Return String. Format ("<LabelFor= '{0}'> {1} </label>", Target, text );

}

}

}

An extension method is created and an application is successfully generated.ProgramThen, the extension method will appear in visual stuidio's intelligent perception, as if all other methods of this class are the same (2 ). The only difference is that there is a special flag (a down arrow icon) next to the extension methods when they appear ).

Figure 2: using HTML. Label () Extension

The modified index view in code listing 6 uses the HTML. Label () Extension Method to present all its <label> labels.

Code List 6-viewshomeindex3.aspx

<% @ Page Language = "C #" autoeventwireup = "true" codebehind = "index3.aspx. CS "inherits =" mvcapplication1.views. home. index3 "%> <% @ import namespace =" mvcapplication1.helpers "%> <! 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> index3 </title>

</Head> <body>

<Div>

<% Using (html. beginform ())

{%>

<% = Html. Label ("firstname", "First name:") %>

<Br/>

<% = Html. Textbox ("firstname") %>

<Br/>

<% = Html. Label ("lastname", "Last Name:") %>

<Br/>

<% = Html. Textbox ("lastname") %>

<Br/>

<Input type = "Submit" value = "register"/>

<% }%>

</Div>

</Body>

</Html>

5. Summary

In this tutorial, you learned two ways to create custom HTML helpers. First, you learned how to create a custom label () HTML helper by creating a static method for returning strings. Next, you learned how to create a custom label () HTML helper method by creating extension methods on the htmlhelper class.

In this call, I will focus on creating extremely simple HTML helper methods. You should be aware of the complexity of HTML helper. You can create HTML helpers to present rich content, such as a tree structure, menu, or database data table.

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.