"ASP. NET MVC Learning Notes"-extension method for Htmlhlper

Source: Internet
Author: User

This article references:http://www.cnblogs.com/willick/p/3428413.html

1, in the MVC used to generate Html elements of the auxiliary class is the SYSTEM.WEB.MVC namespace under the HtmlHelper, it is customary for us to htmlhelper in the (extension) method called HtmlHelper methods, referred to as helper method 。 Its role is to give the task of generating HTML code to MVC so that MVC can do a lot of automated work. The Html.ActionLink, Html.BeginForm, Html.checkbox, Html.raw methods that we use in View are all htmlhelper extension methods.

2, through the custom HtmlHelper extension method we can package a large piece of HTML into a method for repeated calls in the application.

//1. Custom extension Methods Public Static classCustomhelpers { Public StaticMvchtmlstring striphtml ( ThisHtmlHelper HTML,stringinput)
{
//Remove HTML tags from input return NewMvchtmlstring (System.Text.RegularExpressions.Regex.Replace (Input,"<.*?>",string. Empty)); }}//2. Call@{Viewbag.title="Index";} @helper striphtml (stringinput)
{@System. Text.RegularExpressions.Regex.Replace (Input,"<.*?>",string. Empty)}<div>HTML Content: @HttpUtility. HtmlDecode ("<div><p>Test</p><br/></div>"//mvc automatically encodes the string passed from the controller to the view, which is a protection mechanism that allows the background to pass to the view string without the HTML element.
Conflict, and also avoids the use of markup language to attack the site's behavior.
However, the mvchtmlstring returned by the HtmlHelper extension method is trusted by the razor engine, and razor does not encode it
All others need to be encoded and therefore need to be decoded
<br/>Plain Content: @StripHtml ("<div><p>Test</p></div>")</div>

3. List of Helper Method for generating <input> tags:

The first parameter of each HtmlHelper extension method listed corresponds to the Name property of the input element (which is also the ID property by default), and the second parameter specifies the value of the INPUT element.

Each method has an overloaded method with a string type argument, such as Html.textbox ("DataValue"). For this overloaded method, the MVC framework looks for values from ViewBag and @Model in turn. Like the Html.textbox ("DataValue") method, MVC looks for Viewbag.datavalue and @Model. DataValue values as the value of the generated input. Example:

@{    "Index";     " The value from ViewBag. " ;} @Html. TextBox ("datavalue"

the generated HTML code is:

<input id="datavalue" name="datavalue " type= " text  value="Thevalue from ViewBag. "

The Helper method in the list above has a corresponding strongly typed version, such as the Html.checkbox method for the Html.checkboxfor method. Their parameters are lambda expressions, such as:

Html.textboxfor (x = x.firstname)

The generated HTML code is:

<input id="FirstName" name="FirstName " type= " text  "value= " "/>

4. The HtmlHelper extension method to generate the Select tag:

5. MVC provides another set of htmlhelper extension methods that generate HTML elements that can generate the desired HTML tags through the Model information. For example, to generate a text box you can use the Html.editor method.

We can use the model metadata (METADATA) represented by the C # feature to tell helper how to render HTML elements for model. such as:

 Public class Person {     [Hiddeninput (Displayvalue=false)]    publicint  Getset;}     

When you pass @Html. Editorformodel or @Html. editorfor (M = M.personid) method In view, a hidden INPUT element is generated, as follows:

<input id="PersonId" name="PersonIdtype="  Hidden" value="0" />

6. Sometimes the templates provided by MVC do not meet our needs, and we can customize a Helper Method template for a property of the Model object. For example: For frequently used drop-down lists, we can make it into a template. The following example makes a drop-down list template by making a Role enumeration type (defined earlier).

By convention, the MVC framework looks for a custom template under the /views/shared/editortemplates folder. So we need to add a EditorTemplates folder, and then add a role.cshtml file under that folder with the following code:

New SelectList (Enum.getnames (Model.gettype ()), model.tostring ()))

This makes the template a good one. Examples of Use:

To make this feature more generic, so that all enum types can be displayed as a drop-down list, let's change this feature. Delete the original role.cshtml file and create a new enum.cshtml partial view in the same directory, with the following code reference:

= = m, enum.getvalues (Model.gettype ()). Cast<enum>()    = {        string enumval = enum.getname (Model.gettype (), M) ;         return New SelectListItem () {            = (model.tostring () = = enumval)            ,= enumval            ,= enumval        }    ))

Then we can apply it through the UIHint feature in the Model, as follows:

 public  class   person 
{ public int PersonId {get ; set ;} //Specifies that the template name is enum [ UIHint ( " enum " )] Span style= "COLOR: #0000ff" >public role role {get ; set ;}}

Note that MVC is looking for a custom template under the/views/shared/editortemplates directory based on the type of the property, so be sure to ensure that the template's file name and property type name match (or specify the name of the template with the UIHint attribute).

In addition, if the custom template and the built-in template have the same name, MVC uses the custom. This feature can be used to replace the built-in system with a custom template.

"ASP. NET MVC Learning Notes"-extension method for Htmlhlper

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.