开发者

How to get Url.Action inside extension method

I'm using MVC3 (VB) with the Razor view engine, and I'm using the Chart helper to create a number of charts. I've got this code working:

In the view:

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

which triggers this action in the Chart controller:

    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

Because I have a number of charts on a number of views, I wanted to put the creation of the img into a helper function. I thought the following would work:

<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

When I try that though, I get the following error:

OutputStream is not available when a custom TextWriter is used.

I thought calling "htmlHelper.Action" would just generate the URL so I could add it to the img, but it's actually triggering the action. How do I get the equivalent of "Url.Action" from within the extension method?


Simply instantiate an UrlHelper and call the Action method on it:

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

Also I would recommend you to use a TagBuilder to ensure that the markup that you are generating is valid and that the attributes are properly encoded:

<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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜