. Net mvc custom Html helper method,. netmvc custom helper

Source: Internet
Author: User

. 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 ()

Related Article

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.