如何将ActionLink设置为图像

时间:2012-01-03 17:04:46

标签: asp.net-mvc-2

我有一个小问题。如何将ActionLink设置为这样的图像:

 <%= Html.ActionLink("English", "ChangeCulture", "Account",
 new {lang = "en", returnUrl = this.Request.RawUrl }, null)%>

对于其他ActionLink,我做了类似这样的事情:

 Html.ActionLink(" ", "About", "Home", new
 {style = "background: url('../../Content/images/img03.jpg')no-repeat center
 right;display:block; height:24px; width:24px;"})    

但是对于这个例子它不起作用。我想以标志图像的形式向我的网站添加本地化。提前谢谢。

2 个答案:

答案 0 :(得分:0)

我在这里看到一些问题......

首先,您要使用Html样式设置ActionLink的routeValues参数。在它们之间添加一个空对象:

Html.ActionLink(" ", "About", "Home", null, new
 {style = "background: url('../../Content/images/img03.jpg')no-repeat center
 right;display:block; height:24px; width:24px;"})

其次,当您使用相对路径时,您将需要检查图像的URL是否正确。尝试使用Url.Content来获取正确的路径。

第三,url和no-repeat标志之间缺少空格可能会影响浏览器输出。

答案 1 :(得分:0)

我已经使用html helper

解决了这个问题

我会建议使用TagBuilder进行此操作。

  /// <summary>
  /// Create image representation of boolean in form of
  /// </summary>
  /// <param name="html">The HTML.</param>
  /// <param name="boolValue">if set to <c>true</c> [bool value].</param>
  /// <param name="path">The path.</param>
  /// <param name="alt">The alt.</param>
  /// <returns>
  /// html img tag
  /// </returns>
public static string ImageForBool(this HtmlHelper html, bool boolValue, string path,ImageAlt alt)
{
  string trueVal = "tick";
  string falseVal = "x";
  string img = "<img src=\"{0}\" {1}/>";
  string altTag = string.Empty;
  path += "Content/Actions/";
  if (boolValue)
  {
    altTag = (alt == null) ? "" : "alt=\"" + alt.trueOption + "\"";
    return string.Format(img, Path.Combine(path, trueVal) + ".png", altTag);
  }
  else
  {
    altTag = (alt == null) ? "" : "alt=\"" + alt.falseOption + "\"";
    return string.Format(img, Path.Combine(path, falseVal) + ".png", altTag);
  }
}

此选项可能是最适合您的

替代方式

使用html动作链接并使用string.replace 使用你的代码:

string tag = Html.ActionLink("[toReplaceWithImage]", "ChangeCulture", "Account",
 new {lang = "en", returnUrl = this.Request.RawUrl }, null).ToString()

tag.Replace("[toReplaceWithImage]", "<img src=\"path\">");