使用@ Ajax.ActionLink动态图像和格式化参数

时间:2012-03-18 22:27:42

标签: ajax asp.net-mvc-3 razor

我正在尝试将以下工作代码更改为Ajax。

   <a href="@Url.Action("Index", new { pn = pc })"> 
   <img src="@Url.Content("~/Photos/" + @photoFile[pc])", id = "imgnb" width = "100px" height = "150px" alt = "Photo" /></a>  <br />

代码需要处理字符串[]变量,@ photoFile [pc]),并采用格式化,(id =“imgnb”width =“100px”height =“150px”alt =“Photo”)。 (imgnb是css,没有图像边框)

Soe Moe在这里建立了一个Ajax助手Problem with ajax.actionlink helper, return string

他的代码适用于没有参数的静态图像。

         @Ajax.ImageActionLink("../../Photos/Children/albersona1.jpg", "Index", new { pn = pc }, new AjaxOptions
    {
      UpdateTargetId = "Selected Thumbnail",
      InsertionMode = InsertionMode.Replace,
      HttpMethod = "GET" })

有谁知道如何修改此帮助程序以将URL.Action转换为Ajax,以便它处理动态图像和格式化参数。

非常感谢任何帮助。

谢谢,乔

1 个答案:

答案 0 :(得分:3)

public static class ImageActionLinkHelper
{
    public static IHtmlString ImageActionLink(
        this AjaxHelper helper,
        string imageUrl,
        string actionName,
        object routeValues,
        object htmlAttributes,
        AjaxOptions ajaxOptions
    )
    {
        var builder = new TagBuilder("img");
        builder.MergeAttribute("src", imageUrl);
        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
        var html = link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing));
        return new HtmlString(html);
    }
}

然后:

@Ajax.ImageActionLink(
    Url.Content("~/Photos/" + photoFile[pc]),
    "Index",
    new { pn = pc },
    new { id = "imgnb", width = "100px", height = "150px", alt = "Photo" },
    new AjaxOptions
    {
        UpdateTargetId = "foo"
    }
)