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