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

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

我将 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/

相关文章:

c# - 具有多个不同提交按钮的 MVC Razor 表单?

c# - 在 .cshtml 页面中发送和接收数据

asp.net-mvc-3 - Visual Studio web dev express 挂起添加 Entity Framework

asp.net-mvc-3 - 在 Razor View 中与通用方法一起使用

python - 比较带斜杠和 www 的 url

javascript - 检查是否存在带有 Firefox 扩展的 Javascript 的 URL

javascript - window.location.assign(var String) 不起作用

c# - 如何使用 asp.net mvc 和单元测试组织代码和测试

c# - 根据条件显示 DropdownList 的最佳方法

c# - 启用 bool 值并在 View 中输入文本,然后传回 Controller - MVC