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

gfr*_*zle 2 url extension-methods razor asp.net-mvc-3

我正在使用MVC3(VB)和Razor视图引擎,我正在使用Chart帮助器来创建许多图表.我有这个代码工作:

在视图中:

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

在Chart控制器中触发此操作:

    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
Run Code Online (Sandbox Code Playgroud)

因为我在许多视图上有许多图表,所以我想把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
Run Code Online (Sandbox Code Playgroud)

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

OutputStream is not available when a custom TextWriter is used.
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*rov 6

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

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

另外,我建议您使用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
Run Code Online (Sandbox Code Playgroud)