ASP. NET MVC Development Basics Learning Notes: ii. HtmlHelper and extension methods

Source: Internet
Author: User
Tags actionlink

One powerful page development helper class-htmlhelper get an initial look at 1.1.

In ASP. Microsoft does not provide a way to develop a server-side control, after all, Microsoft's MVC is the regression of traditional request processing responses . So discarding the model of the previous event response and discarding the server-side control is a natural thing.

However, if the handwritten HTML tags are inefficient, the reusability is relatively low . At this point, how can we improve efficiency? First, we know we can pass the data through ViewData, so we can write the following HTML code:

<input name= "UserName" type= "text" value= "<%: viewdata[" UserName "]%>"/>

Although the above code can solve the problem, but the efficiency is relatively low, especially in the list of collection items, the workload will be relatively large. So, is there a better way of wood? Don't worry, Microsoft has figured out a strategy for us. Microsoft provides a Rich HtmlHelper helper class for developers to quickly develop front page, which helps us to quickly develop front page, also provides extensible interface, the front page label can be highly reusable .

First Glimpse of 1.2 htmlhelper

We can implement fast Html tag editing through html.xxx on the page, and can easily be used for data binding.

<%: Html.raw ("<p>hello,i am htmlhelper!</p>")%>

So why do you call the Html.xxx method in the page? By Ilspy The ViewPage page, we can see that the original property-html has a htmlhelper type under ViewPage. (This finally knows why you can use HTML.XXXX () in the page)

So what kind of a great God is this HtmlHelper class? Continue the anti-compilation view, as shown in the HtmlHelper type under the SYSTEM.WEB.MVC namespace, HtmlHelper supports rendering HTML controls in the view, as illustrated by the MSDN Great God. So let's see if there is a legend of the textbox in this class, the CheckBox method? After viewing, the wood has.

So why do we use the Html.textbox () method on the page? This involves a thing called "extension method", theextension method of HtmlHelper class is SYSTEM.WEB.MVC.  The Html namespace. These extensions add helper methods for creating forms, rendering HTML controls, rendering partial views, performing input validation, and so on. So, for how to customize the extension method, see the third part of this article, here first sell a Xiaoguanzi, temporarily do not introduce.

1.3 Why use HtmlHelper?

Consider a scenario in which the routing rules in the first version of our project are {Controller}/{action}/{id}, so all the <a> tags in our project point to the href named by the just rule (for example: <a href= ' HOME/USER/1 ' ></a>). However, in the second edition, our routing rules will also become {Controller}-{action}-{id}, then we have just set the hyperlink to the HREF will not be able to access the normal. At this point, we need to replace, a single replacement or bulk replacement (for example, <a href= ' home-user-1 ' ></a>), although it can also solve the problem, but undoubtedly increased the workload, inefficient.

So, how to block the inconvenience caused by this change? Here, we can solve this problem by using the ActionLink tag provided by HtmlHelper. Because HtmlHelper automatically helps you generate a tag from the server side, the resulting href will follow the current routing rules, which will help us block changes and improve productivity.

Second, no server control can do big things-htmlhelper Important method Introduction

  PS: None of the examples here Add <%%> or @ symbol, to run please add it yourself.

(1) ActionLink and RouteLink

Html.ActionLink ("This is a connection", "index", "Home") with QueryString notation Html.ActionLink ("This is a connection", "index", "home", new {page=1}, NULL) Html.ActionLink ("This is a connection", "index", new {page=1}) has other Html attributes written Html.ActionLink ("This is a connection", "Index", "Home", new {id= " Link1 "}) Html.ActionLink (" This is a connection "," Index ", NULL, new {id=" Link1 "}) querystring with the Html attribute exists Html.ActionLink (" This is a connection "," Index "," Home ", new {page = 1}, new {id =" Link1 "}) Html.ActionLink (" This is a connection "," Index ", new {page = 1}, new {id =" L Ink1 "})

The result of the build is:

<a href= "/" > This is a connection </a> with QueryString notation <a href= "/?page=1" > This is a connection </a><a href= "/?page=1" > This is a connection </a> has other HTML attributes written <a href= "/? Length=4 "id=" Link1 "> This is a connection </a><a href="/"id=" Link1 "> This is a connection </a>querystring and HTML attributes exist at the same time <a href= "/?page=1" id= "Link1" > This is a connection </a><a href= "/?page=1" id= "Link1" > This is a connection </a>

RouteLink in the use of almost the same as ActionLink, here is no longer introduced, please participate in MSDN details;

(2) TextBox and textarea

①textbox

Html.textbox ("Input1") Html.textbox ("Input2", model.categoryname,new{@style = "width:300px;"}) Html.textbox ("Input3", viewdata["Name"],new{@style = "width:300px;"}) Html.textboxfor (A = A.categoryname, new {@style = "width:300px;"})

The result of the build is:

<input id= "input1" name= "input1" type= "text" value= ""/><input id= "Input2" name= "Input2" style= "width:300px;" Type= "text" value= "Beverages"/><input id= "Input3" name= "Input3" style= "width:300px;" type= "text" value= ""/> <input id= "CategoryName" name= "CategoryName" style= "width:300px;" type= "text" value= "Electronic"/>

②textarea

Html.textarea ("Input5", Model.categoryname, 3, 9,null) html.textareafor (a = A.categoryname, 3, 3, NULL)

The result of the build is:

<textarea cols= "9" id= "Input5" name= "Input5" rows= "3" >electronic</textarea><textarea cols= "3" id= " CategoryName "Name=" CategoryName "rows=" 3 ">Electronic</textarea>

As you can see here, we can use strong typing to generate Html tags, for example: html.textboxfor (A = = A.categoryname, new {@style = "width:300px;"}), The CategoryName here is a property of a certain type.

(3) CheckBox

Html.checkbox ("Chk1", True) Html.checkbox ("Chk1", new {@class = "checkbox"}) Html.checkboxfor (a =>a.isvaild, new {@ class = "checkbox"})

The result of the build is:

<input checked= "Checked" id= "Chk1" name= "Chk1" type= "checkbox" Value= "true"/><input name= "Chk1" type= "hidden "Value=" false "/><input class=" checkbox "id=" Chk1 "name=" Chk1 "type=" checkbox "Value=" true "/><input name= "Chk1" type= "hidden" value= "false"/><input checked= "checked" class= "CheckBox" id= "Isvaild" name= "Isvaild" type= "checkbox" Value= "true"/><input name= "Isvaild" type= "hidden" value= "false"/>

(4) DropDownList

Html.dropdownlist ("Ddl1", (selectlist) viewdata["Categories"],  "--select one--") html.dropdownlistfor (A + a). CategoryName, (selectlist) viewdata["Categories"], "--select one--", new {@class = "DropDownList"})

The result of the build is:

<select id= "DDL1" name= "DDL1" ><option value= "" >--select one--</option><option value= "1" > Beverages</option><option value= "2" >condiments</option><option selected= "selected" Value= "3" >confections</option><option value= "4" >dairy products</option><option value= "5" >Grains /cereals</option><option value= "6" >meat/poultry</option><option value= "7" >Produce</ Option><option value= "8" >seafood</option></select><select class= "DropDownList" id= " CategoryName "Name=" CategoryName "><option value=" ">--select one--</option><option value=" 1 "> Beverages</option><option value= "2" >condiments</option><option value= "3" >Confections< /option><option value= "4" >dairy products</option><option value= "5" >Grains/Cereals</option ><option value= "6" >meat/poultry</option><option value= "7" >produce</option><option value= "8" >Seafood</option></select> 

(5) RadioButton

Male <%: Html.radiobutton ("Gender", "1", true)%> female <%: Html.radiobutton ("Gender", "2", false)%>

The generated code is:

Male <input checked= "checked" id= "Gender" name= "Gender" type= "Radio" value= "1"/> female <input id= "Gender" Name= "Gender "Type=" Radio "value=" 2 "/>

(6) Encode and raw

Encode will encode the content, so if your content contains HTML tags then it will be parsed into special characters, such as:

<%: Html.encode ("<p> haha </p>")%>

The generated code is:

&amp;lt;p&amp;gt; haha &amp;lt;/p&amp;gt;

This is primarily to prevent XSS attacks and malicious scripts, so in MVC, the default <%:%> implements the <%: Html.encode ()%>. However, sometimes if we need to output a string of HTML or JavaScript content, we can use the other methods that HtmlHelper gives us. For example we want to output just that sentence, we can use the following:

<%: Html.raw ("<p> haha </p>")%>

The generated code is:

<p> haha </p>

In the HtmlHelper, there are many extension methods to facilitate the creation of HTML, such as: BeginForm, EndForm and so on. For other methods of introduction, please search by yourself, here no longer one by one repeat.

Third, anytime, anywhere I can expand the-htmlhelper extension method Brief Introduction to 3.1 extension methods

With the introduction of MSDN: The extension method enables you to add a method to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type . The extension method is a special static method, but it can be called just like an instance method on an extended type. We can go back to the first part of the HtmlHelper extension class-inputextension class, it is for htmlhelper extension, then how to identify it is the extension of HtmlHelper?

3.2 Three elements of the extension method

(1) Static class

It can be seen from the inputextension that the first is a static class;

(2) static method

Since it is a static class, all of its methods must be static, for example: public static mvchtmlstring CheckBox ();

(3) This keyword

As can be seen from the method name definition, the first parameter is this HtmlHelper HtmlHelper, which represents the extension of the HtmlHelper class;

3.3 Custom extension methods

(1) Create a new class under the Models folder named: Myhtmlhelperext

(2) Set Myhtmlhelperext to static and write to one of the following static methods:

public static htmlstring Myexthtmllabel (This htmlhelper helper, string value) {      return new htmlstring (string. Format ("<span style= ' font-weight:bold; ') >Hello-{0}-End</span> ", value));}

(3) After identifying the three elements that have satisfied the extension method, change the namespace to: SYSTEM.WEB.MVC.

Namespace SYSTEM.WEB.MVC

PS: Why do you want to change the namespace to SYSTEM.WEB.MVC?

This is because if you do not change the namespace, we need to use a custom extension method to introduce the namespace of models (the namespace in which Myhtmlhelper resides) in each page, in order to prevent duplicate namespaces from being introduced (think of us using Html.textbox () No, you didn't introduce namespaces? ), we align the namespace with the namespace where the HtmlHelper class resides.

(4) On the page we can use the extension method we wrote ourselves.

<%: Html.myexthtmllabel ("Edisonchou")%>

(5) View page effects

Reference articles

(1) Mullen, "ASP. Video Tutorial", http://bbs.itcast.cn/thread-26722-1-1.html

(2) OER, "HtmlHelper use Daquan", http://www.cnblogs.com/oer2001/archive/2013/03/19/2968475.html

(3) MSDN, "extension method (C # Programming Guide)", http://technet.microsoft.com/zh-cn/bb383977

(4) MSDN, "HtmlHelper Class (SYSTEM.WEB.MVC)", Http://msdn.microsoft.com/zh-cn/library/system.web.mvc.htmlhelper (v= vs.108). aspx

ASP. NET MVC Development Basics Learning Notes: ii. HtmlHelper and extension methods

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.