. Net mvc custom Html helper method,. netmvc custom helper
Using System;
Using System. Web. Mvc;
Using System. Web. Routing;
Namespace MvcTest2.Helpers
{
Public static class ImageHelpers
{
Public static MvcHtmlString ImgLink (this HtmlHelper helper, string actionName, string imgUrl, string alternateText, object routeValues, object linkHtmlAttributes, object ghtimmlattributes)
{
Var urlHelper = new UrlHelper (helper. ViewContext. RequestContext); // obtain the url help object class of the page from which the page references it.
Var url = urlHelper. Action (actionName, routeValues );
Var linkTagBuilder = new TagBuilder ("a"); // use this method to generate tags
LinkTagBuilder. MergeAttribute ("href", url );
LinkTagBuilder. MergeAttributes (new RouteValueDictionary (linkHtmlAttributes ));
Var imgTagBuilder = new TagBuilder ("img ");
ImgTagBuilder. MergeAttribute ("src", imgUrl );
ImgTagBuilder. MergeAttribute ("alt", alternateText );
ImgTagBuilder. MergeAttribute ("title", alternateText );
ImgTagBuilder. MergeAttributes (new RouteValueDictionary (imgHtmlAttributes ));
LinkTagBuilder. InnerHtml = imgTagBuilder. ToString (TagRenderMode. SelfClosing); // convert it to the tag whose Tag ends.
Return MvcHtmlString. Create (linkTagBuilder. ToString ());
}
}
Method returns a linkImg
Custom Html auxiliary methods must be written to static methods.
Reference Methods on the page
@ Using MvcTest2.Helpers
@ Html. ImgLink ()