Attach image to ActionLink in MVC 4

雨燕双飞 提交于 2019-12-01 04:17:54

问题


I am using ActionLink with id in MVC 4 app and assinging actionLink id an image in css but on on earth I am doing wrong. is not working! here is my code

 <div class="logo_container">
            @Html.ActionLink(" ", "Index", "Home", null, new { id = "_Logo" })
 </div>

CSS

.logo_container {
width:339px;
height:116px; 
}

#_Logo {
background-image: url("../Images/logo.png");
 width:339px;
height:116px;
background-color:green;
}

回答1:


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>



回答2:


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%\" … />"))



回答3:


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) 



回答4:


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>


来源:https://stackoverflow.com/questions/19245343/attach-image-to-actionlink-in-mvc-4

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