MVC Learning Series 4--@helper helper methods and user-defined HTML methods

Source: Internet
Author: User

With the help of HTML helper and helper classes, we can dynamically create HTML controls. The HTML helper class is used in the view to render HTML content. The HTML helper class is a method that returns a string-type value.

HTML helper class, divided into three types:

    1. Inline HTML helpers "Inline HTML helper class, such as @html.label, etc."
    2. Built-in HTML helpers "is a nested HTML helper class, @helper helper method"
    3. Custom HTML Helpers "Customized HTML helper class"

Here, we learn the second, and the third, the first is too simple, here is not introduced. About the first kind, I have introduced in the previous article, we can see.

    1. Built-in HTML helpers "is a nested HTML helper class, @helper helper method"

Start by creating a new, blank MVC project that creates a home controller with the following default code:

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace htmlhelpermvc.controllers{public    class Homecontroller:controller    {        //get:home        Public ActionResult Index ()        {            return View ();}}    }

Add the corresponding index view: Write the @helper helper method in the view:

@{    Layout = null;} <! DOCTYPE html>@* Declaration Helper method Start *@ @helper SayHello (string[] strarray) {    <ol>        @foreach (var item in Strarray)        {            <li>hello: @item </li>        }    </ol>}@* declares the end of the helper method *@

Then run the index method, and the result is:

As can be seen, @helper auxiliary method, very useful, when a block needs multiple use, you can use the @helper helper method

However, you may have seen, this way of writing, I can only in the current page, re-use this @helper helper method, that if I want to use on other pages also????

We add another method to the controller and create the view page:

public class Homecontroller:controller    {        //get:home public        actionresult Index ()        {            return View () ;        }        Public ActionResult Anotherindex ()        {            return View ();        }    }
Anotherindex View:
@{    Layout = null;} <! DOCTYPE html>

So, what do we do now, in order to use the same @helper helper method on all pages???
So, let's add an App_Code folder, and then create a new view inside, and put a copy of the part of the auxiliary method that was just declared, intact.

Then compile the whole project "PS: If not come out smart tips, change, App_Code, the properties of the view, instead


In the page, in the index view, this is called:
@{    Layout = null;} <! DOCTYPE html>

In the Anotherindex view:
@{    Layout = null;} <! DOCTYPE html>

The result is the same, and now the difference is that you can use the same helper method on multiple pages.

2.Custom HTML Helpers "Custom HTML helper Class"

Now look at the second type, the custom HTML helper class:

We can create 2 ways to customize the helper class:

1.Using static Methods "method of use statically"
2.Using extension methods "using extension method"

First look at how it's done using static methods.

Create a new Folder "Customerhelper" and create a new helper class "Customerhelperclass" under Customerhelper

In the Help class, we create a new static method CreateImage:

Using system;using system.collections.generic;using system.linq;using system.web;//mvchtmlstring need to introduce namespaces using         System.web.mvc;namespace htmlhelpermvc.customerhelper{public class Customerhelperclass {//<summary> static method, create image///</summary>//<param name= "ImageSource" > Picture source </param>/ <param name= "AltText" > Alt attribute value of picture </param>//<param name= "width" > Width </param>///&L T;param name= "hight" > Height </param>//<returns></returns> public static mvchtmlstring Cre            Ateimage (String ImageSource, String alttext, string width, string hight) {//Create an IMG tag via Tagbuilder            Tagbuilder Imagetag = new Tagbuilder ("img");            Mergeattribute Add new feature Imagetag.mergeattribute ("src", imagesource);            Imagetag.mergeattribute ("alt", AltText);            Imagetag.mergeattribute ("width", width); Imagetag.mergeattribute ("HiGht ", hight); Mvchtmlstring.create, using the specified literal value, creates an HTML-encoded string of return Mvchtmlstring.create (Imagetag.tostring (TAGRENDERMODE.SELFC        Losing)); }    }}

Then we call in the view:

@{    Layout = null;} <! DOCTYPE html> @using htmlhelpermvc.customerhelper

The result is:

You can see the static method and create an image control for us, and the above call requires a using auxiliary class:

@using Htmlhelpermvc.customerhelper

Is it very troublesome to have the using of each time???

We can add this sentence in the view's configuration file:

By the way, change the properties of the configuration file:

In compiling:

After that, we get rid of the view page

@using Htmlhelpermvc.customerhelper

The results are the same.

In other words, the way to extend the method, customize the auxiliary HTML bar:

In fact, this is even more simple, is simply the extension method, extending the HtmlHelper class:

Using system;using system.collections.generic;using system.linq;using system.web;//mvchtmlstring need to introduce namespaces using System.web.mvc;namespace htmlhelpermvc.customerhelper{public static class Customerhelperclass {//<summ        ary>///static method, create image///</summary>//<param name= "ImageSource" > Picture source </param>        <param name= "AltText" > Alt attribute value of picture </param>//<param name= "width" > Width </param> <param name= "hight" > Height </param>//<returns></returns> public static MVCHTMLSTR            ing createimage (string imagesource, String alttext, string width, string hight) {//Create an IMG tag via Tagbuilder            Tagbuilder Imagetag = new Tagbuilder ("img");            Mergeattribute Add new feature Imagetag.mergeattribute ("src", imagesource);            Imagetag.mergeattribute ("alt", AltText);            Imagetag.mergeattribute ("width", width); Imagetag.mergeattribUte ("Hight", hight); Mvchtmlstring.create, using the specified literal value, creates an HTML-encoded string of return Mvchtmlstring.create (Imagetag.tostring (TAGRENDERMODE.SELFC        Losing)); } public static mvchtmlstring createimage (This htmlhelper htmlhelper, string ImageSource, String AltText, String wi            DTH, String hight) {//Create an IMG tag tagbuilder imagetag = new Tagbuilder ("img") via Tagbuilder;            Mergeattribute Add new feature Imagetag.mergeattribute ("src", imagesource);            Imagetag.mergeattribute ("alt", AltText);            Imagetag.mergeattribute ("width", width);            Imagetag.mergeattribute ("Hight", hight); Mvchtmlstring.create, using the specified literal value, creates an HTML-encoded string of return Mvchtmlstring.create (Imagetag.tostring (TAGRENDERMODE.SELFC        Losing)); }    }}

Call in the view:

@{    Layout = null;} <! DOCTYPE html>

MVC Learning Series [email protected] helper methods and user-defined HTML 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.