创建一个帮助方法来替换锚html标记

时间:2011-12-20 11:39:05

标签: asp.net-mvc

在我看来,我使用以下代码从我的数据库中获取图像(通过操作方法)并将其显示在html标记中

<img src="@Url.Action("DownloadBackground", new { projectID = 31 })" />

名为DownloadBackground的Action方法返回一个FileContentResult,其中包含存储在我的数据库中的图像。它有效,但我想创建一个帮助方法来替换它。

我想要像:

@Html.BackgroundFor(31) 

其中31是我需要的项目的ID。我希望这个帮助方法能够生成相同的html代码。

所以我尝试创建这样的帮助:

public static MvcHtmlString BackgroundFor(this HtmlHelper helper, int id)
{
    // What code here ?? 

    var builder = new TagBuilder("a");
    builder.MergeAttribute("src", ???);
    return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}

1 个答案:

答案 0 :(得分:1)

试试这个:

builder.MergeAttribute("src", new UrlHelper(helper.ViewContext.RequestContext)
                                    .Action("DownloadBackground",
                                            new { projectID = id }));

或者,您可以使用

new UrlHelper(((MvcHandler)HttpContext.Current.Handler).RequestContext)

这也会这样做