Using system;using system.collections.generic;using system.linq;using system.text;using System.Web;using System.web.mvc;namespace myef.extentionhtmlhelper{public static class Imagehelper {//Description: Because the c#3.0 expansion method is a special kind of static The HTML helper method must be declared as a//static method and placed in a static category! There is also a point in the custom HTML method, which is that from the HTML helper method, The type of callbacks can make a simple string string type, can also be the System.Web.MvcHtmlString category, the difference is that through the Rasor output HTML presets will be all the output HTML encoding action, so if the callback string string type, its output will be HTML encoded output, if you return from the HTML helper method m Vchtmlstring type, if the content contains tag data, then it will output HTML tags intact, in our case, we must return the mvchtmlstring category, the code example is as follows: public static mvchtmlstring H Tmlimg (This htmlhelper helper, string url, String AlternateText, string title) {return MVCHTMLSTRING.CR Eate (String. Format (" "); Sb. Append ("</a> "); Return Mvchtmlstring.create (sb.) ToString ()); } }}
This way of using the StringBuilder group of substrings has no elasticity, and ASP. NET MVC specifically designed a tagbuilder category to produce HTML tags that can produce HTML tags in a more structured way, and then rewrite the example above. The Tagbuilder instance is as follows:
public static mvchtmlstring ImageLink (this htmlhelper helper,string actionname,string imgurl, String AlternateText, Object Routevalues,object linkhtmlattributes,object imagehtmlattributes) {var urlhelper = new Urlhelper (helper.) Viewcontext.requestcontext); var url = urlhelper.action (ActionName, routevalues); Establish link var linktagbuilder = new Tagbuilder ("a"); Linktagbuilder.mergeattribute ("href", url); Linktagbuilder.mergeattributes (New RouteValueDictionary (linkhtmlattributes)); Create picture var imagetagbuilder = new Tagbuilder ("img"); Imagetagbuilder.mergeattribute ("src", urlhelper.content (Imgurl)); Imagetagbuilder.mergeattribute ("alt", AlternateText); Imagetagbuilder.mergeattribute ("title", AlternateText); Imagetagbuilder.mergeattributes (New Viewdatadictionary (imagehtmlattributes)); Add the picture to the connection linktagbuilder.innerhtml = Imagetagbuilder.ToString (tagrendermode.selfclosing); Return Mvchtmlstring.create (Linktagbuilder.tostring ()); }
ASP. NET MVC4.0 Custom HTML helper method