【发布时间】:2010-11-02 14:32:13
【问题描述】:
除了将生成的链接放在图像周围而不是仅仅吐出链接之外,我该如何做类似于 Html.ActionLink() 的事情?
【问题讨论】:
标签: asp.net-mvc
除了将生成的链接放在图像周围而不是仅仅吐出链接之外,我该如何做类似于 Html.ActionLink() 的事情?
【问题讨论】:
标签: asp.net-mvc
Razor(查看引擎):
<a href="@Url.Action("ActionName", "ControllerName")">
<img src="@Url.Content("~/Content/img/imgname.jpg")" />
</a>
ASPX(视图引擎):
<a href="<%= Url.Action("ActionName", "ControllerName") %>">
<img src="<%= Url.Content("~/Content/img/imgname.jpg") %>" />
</a>
显然,如果您不止一次这样做,请为它编写一个帮助程序。并填写img/a的其他属性。但这应该可以让您大致了解。
【讨论】:
试试这样的:
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);
}
希望对你有帮助
【讨论】:
TagRenderMode.Normal 更改为 TagRenderMode.SelfClosing;否则呈现为<img...></img> 而不是<img.../>
@Craig Stuntz 给出的第一个答案是绝对完美的,但我担心的是,如果你有 Ajax.ActionLink 而不是 Html.ActionLink,你会怎么做。在这里,我将解释这两种方法的简单解决方案。您可以对Html.ActonLink 执行以下操作:
@Html.Raw(@Html.ActionLink("[replacetext]", "Index", "Home").ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" ... />"))
同样的概念可以应用于Ajax.ActionLink
@Html.Raw(@Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" … />"))
所以这对你来说很容易。
编辑:
带有样式表或类名的 ActionLink 图像
带样式表
@Html.Raw(@Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" style=\"width:10%\" ... />"))
类名
<style>
.imgClass {
width:20%
}
@Html.Raw(@Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" class=\"imgClass\" ... />"))
如需更多关于 Image 周围 ActionLink 的参考,请访问ActionLink around Image in Asp.net MVC
【讨论】:
更简单...
通过以下方式更改您的代码:
<p class="site-title">@Html.ActionLink(" ", "Index", "Home",
new
{
style = "background: url('" + Url.Content("~/images/logo.png") + "') no-repeat center right; display:block; height:50px;width:50px;"
})</p>
【讨论】:
你可以使用 url.content:
@Url.Content("~/images/img/slide.png")
这个返回相对路径
【讨论】:
您可以创建htmlhelper,它可以返回带有链接的图像... 作为参数,您将传递给 htmlhelper 值,例如图像路径和链接,在 htmlhelper 中,您将使用 StringBuilder 正确格式化链接图像的 html...
干杯
【讨论】: