Attach image to ActionLink in MVC 4

ε祈祈猫儿з 提交于 2019-12-01 07:35:22

This is from my application. Works ok:

.logo{
background:no-repeat url(/Content/photo/png/sprite.png) 0 0;
height:15px;
width:20px;
overflow:hidden;
float:left;
border:none;
display:inline;
}

<a href="@Url.Action("Action", "Controller")" class="logo"></a>
Dilip0165

The best way you can do for both Html.ActionLink and Ajax.ActionLink is as below

@Html.Raw(@Html.ActionLink("[replacetext]", "Index", "Home").ToHtmlString().Replace("[replacetext]", "<img src=\"/Content/img/logo.png\" ... />"))


@Html.Raw(@Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" … />"))

additionaly you want to provide class and style so you can do as following

@Html.Raw(@Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" style=\"width:10%\" … />"))

use your custom HtmlHelper:

    namespace Order.Web.UI.Infrastructure
{
    public static class CustomHelpers
    {
        public static MvcHtmlString ImageActionLink(this HtmlHelper html, string imageSource, string url)
        {
            string imageActionLink = string.Format("<a href=\"{0},\"><img width=\"150\" height=\"150\" src=\"{1}\" /></a>",url,imageSource);

            return new MvcHtmlString(imageActionLink);
        }
    }
}

then in your view.cshtml:

@using OrderPad2.Web.UI.Infrastructure
.
.
.
.
@Html.ImageActionLink(@app.Icon,@app.AppStoreLink) 
Mike

You only needed to change:

new { id = "_logo"}

to:

new { @id = "_logo"} 

Without the @ in front of id it treats it as a parameter instead of a attribute of the html element.

Without the @, it would produce:

www.site.com/home/index/_logo

With the @, it would produce:

www.site.com/home

and the element would be:

<a id="_logo" href=""></a>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!