How can I do something similar to Html.ActionLink() except place the generated link around an Image instead of just spitting out the link?
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.
Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.
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).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With