. Net mvc extension methods must be defined in non-generic static classes

Source: Internet
Author: User

The. net mvc extension method is also a static method and can be called as an instance method.

Features of extension methods in. net mvc 3:

(1) The extension class name ends with Extensions;

(2) The type of the extension class is static;
(3) The extension method must have at least one parameter. The first parameter must specify the type of the method to act on and useThisThe modifier is the prefix;

(4) The extension method type is static;

(5) If the return value of the extended method is a string, the return type is MvcHtmlString, not string;

(6) The page call must use the using command to import the namespace of the extension type.

For specific cases, refer to the following code:

1. Create an extension class HtmlExtensions and create the extension method StringTruncate in it. For specific code, refer to code 1.1 (this method is used by common website technologies, that is, intercepting strings)

Code 1.1:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace TestAllMVC.Helps{    public static class HtmlExtensions    {        public static MvcHtmlString StringTruncate(this HtmlHelper htmlHelper, string input, int length)        {            if (input.Length <= length)            {                return MvcHtmlString.Create(input);            }            else            {                return MvcHtmlString.Create(input.Substring(0, length) + "...");            }        }    }}
2. In this example, the Razor view engine is used to create Index. cshtml. The Code is as follows: Code 2.1

Code 2.1:

@ {ViewBag. Title = "Home Page" ;}@ using TestAllMVC. Helps; @ Html. StringTruncate ("Diaoyu Islands are from China! It has been an inseparable and holy territory of China since ancient times. ", 8)
3. Result 3.1

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.