如何在扩展方法中获取Url.Action

时间:2011-09-23 16:06:45

标签: asp.net-mvc-3 url razor extension-methods

我正在使用带有Razor视图引擎的MVC3(VB),我正在使用Chart帮助程序来创建许多图表。我已经有了这段代码:

在视图中:

<img src="@Url.Action("Rpt002", "Chart", New With {.type = "AgeGender"})" alt="" />

在图表控制器中触发此操作:

    Function Rpt002(type As String) As ActionResult
        Dim chart As New System.Web.Helpers.Chart(300, 300)
        '...code to fill the chart...
        Return File(chart.GetBytes("png"), "image/png")
    End Function

因为我在许多视图上有许多图表,所以我想将img的创建放入辅助函数中。我认为以下内容可行:

<System.Runtime.CompilerServices.Extension>
Public Function ReportChart(htmlHelper As HtmlHelper, action As String, type As String) As MvcHtmlString

    Dim url = htmlHelper.Action(action, "Chart", New With {.type = type})
    Return New MvcHtmlString(
        <img src=<%= url %> alt=""/>
    )

End Function

当我尝试时,我收到以下错误:

OutputStream is not available when a custom TextWriter is used.

我认为调用“htmlHelper.Action”只会生成URL,所以我可以将它添加到img中,但它实际上是在触发动作。如何从扩展方法中获得“Url.Action”的等效内容?

1 个答案:

答案 0 :(得分:6)

只需实例化UrlHelper并在其上调用Action方法:

Dim urlHelper as New UrlHelper(htmlHelper.ViewContext.RequestContext);
Dim url = urlHelper.Action(action, "Chart", New With {.type = type})

我还建议您使用TagBuilder来确保您生成的标记有效并且属性已正确编码:

<System.Runtime.CompilerServices.Extension> _
Public Shared Function ReportChart(htmlHelper As HtmlHelper, action As String, type As String) As IHtmlString
    Dim urlHelper = New UrlHelper(htmlHelper.ViewContext.RequestContext)
    Dim url = urlHelper.Action(action, "Chart", New With { _
        Key .type = type _
    })
    Dim img = New TagBuilder("img")
    img.Attributes("src") = url
    img.Attributes("alt") = String.Empty
    Return New HtmlString(img.ToString())
End Function