1

How can i create action image html helper in asp.net mvc like below..

@Html.ActionImage("actionName", "controllerName", "routeValues")

similarly like below helper...

@Html.Action("actionName", "controllerName", "routeValues")

Thanks in advance.....

1
  • 1
    what's your problem with Action? You always can create controller that returns image. Commented Sep 17, 2015 at 13:02

2 Answers 2

2

You can create custom helper class like..

 namespace MyNamespace 
 {  
    public static class MyHeleprs
    { 
        public static MvcHtmlString ActionImage(this HtmlHelper html, string actionName, string controllerName, object routeValues, string imagePath, string alt)
         {
             var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));
            imgBuilder.MergeAttribute("alt", alt);
            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");

            anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
         } 
    } 
}

To make this helper available in your view, add its namespace as follows:

@using MyNamespace

Now you can get html helper in your views like below...

@Html.ActionImage(actionName, controllerName, routeValues, imagePath, imgAlt)
Sign up to request clarification or add additional context in comments.

Comments

2

Try this custom Html helper:

public static IHtmlString ImageActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes,string imageSrc)
{
                var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
                var img = new TagBuilder("img");
                img.Attributes.Add("src", VirtualPathUtility.ToAbsolute(imageSrc));
                var anchor = new TagBuilder("a") { InnerHtml = img.ToString(TagRenderMode.SelfClosing) };
                anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
                anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));

                return MvcHtmlString.Create(anchor.ToString());

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.