Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an Html.ActionLink around an Image in ASP.NET MVC?

Tags:

asp.net-mvc

How can I do something similar to Html.ActionLink() except place the generated link around an Image instead of just spitting out the link?

like image 561
KingNestor Avatar asked Jun 12 '09 20:06

KingNestor


People also ask

What is HTML ActionLink in MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

What is the difference between using URL action and HTML ActionLink in a view?

Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.

How do I pass an object in ActionLink?

If you need to pass through the reference to an object that is stored on the server, then try setting a parameter of the link to give a reference to the object stored on the server, that can then be retrieved by the action (example, the Id of the menuItem in question).


2 Answers

Try something like this:

public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName) {     var urlHelper = new UrlHelper(html.ViewContext.RequestContext);      string imgUrl = urlHelper.Content(imgSrc);     TagBuilder imgTagBuilder = new TagBuilder("img");     imgTagBuilder.MergeAttribute("src", imgUrl);     string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing);      string url = UrlHelper.Action(actionName);      TagBuilder tagBuilder = new TagBuilder("a") {         InnerHtml = img     };     tagBuilder.MergeAttribute("href", url);      return tagBuilder.ToString(TagRenderMode.Normal); } 

Hope this helps

like image 32
eu-ge-ne Avatar answered Oct 21 '22 04:10

eu-ge-ne


Razor (View Engine):

<a href="@Url.Action("ActionName", "ControllerName")">     <img src="@Url.Content("~/Content/img/imgname.jpg")" /> </a> 

ASPX (View Engine):

<a href="<%= Url.Action("ActionName", "ControllerName") %>">     <img src="<%= Url.Content("~/Content/img/imgname.jpg") %>" /> </a> 

Obviously, if you do this more than once, write a helper for it. And fill in the other attributes of img/a. But this should give you the general idea.

like image 70
Craig Stuntz Avatar answered Oct 21 '22 02:10

Craig Stuntz