我在Razor View 引擎中使用了MVC3(VB),并且在使用图表助手来创建许多图表。我有此代码的工作:
在 View 中:
<img src="@Url.Action("Rpt002", "Chart", New With {.type = "AgeGender"})" alt="" />
这会在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
因为我在许多 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”?
最佳答案
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/