gpt4 book ai didi

asp.net-mvc-3 - 如何在扩展方法中获取 Url.Action

转载 作者:行者123 更新时间:2023-12-02 08:52:24 25 4
gpt4 key购买 nike

我将 MVC3 (VB) 与 Razor View 引擎结合使用,并且我正在使用图表助手创建大量图表。我已经让这段代码工作了:

在 View 中:

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

在图表 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

因为我在多个 View 上有多个图表,所以我想将 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”?

最佳答案

简单地实例化一个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

关于asp.net-mvc-3 - 如何在扩展方法中获取 Url.Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7531846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com