【问题标题】:How do I convert this Razor code from C# to VB.NET?如何将此 Razor 代码从 C# 转换为 VB.NET?
【发布时间】:2013-07-26 03:24:05
【问题描述】:

Darin DimitrovThis answer 是一个很好的解决方案,可以将 javascript 放入部分视图但让它们稍后呈现。

我已将 HtmlHelper 扩展转换为 VB.NET,但我不知道如何将它们与 Razor 一起使用。

@Html.Script(@<script></script>)

Expression expected.

@Html.Script(@:<script></script>)

Expression expected.

@Code
    Html.Script(@<script></script>)
End Code

Expression expected.

Syntax error.

@Code
    Html.Script(@:<script></script>)
End Code

Expression expected.

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 razor html-helper


    【解决方案1】:

    在这里。我想到了一种解决方案,即使用 Razor Helpers。

    扩展

    Namespace Helpers.Extensions
    
        Public Module HtmlHelperExtensions
    
            <Extension>
            Public Function Script(helper As HtmlHelper, result As HelperResult) As MvcHtmlString
                helper.ViewContext.HttpContext.Items("_script_" & Guid.NewGuid.ToString) = result
                Return MvcHtmlString.Empty
            End Function
    
            <Extension>
            Public Function RenderScripts(helper As HtmlHelper) As IHtmlString
                helper.ViewContext.Writer.WriteLine("<script type=""text/javascript"">")
                For Each key As Object In helper.ViewContext.HttpContext.Items.Keys
                    If (key.ToString.StartsWith("_script_")) Then
                        Dim result As HelperResult =
                            DirectCast(helper.ViewContext.HttpContext.Items(key), HelperResult)
                        If result IsNot Nothing Then
                            helper.ViewContext.Writer.Write(result)
                        End If
                    End If
                Next
                helper.ViewContext.Writer.WriteLine("</script>")
                Return MvcHtmlString.Empty
            End Function
    
        End Module
    
    End Namespace
    

    剃刀(部分)

    @Html.Script(Javascript)
    
    @Helper Javascript()
    @<text>
    alert("It works");
    </text>
    End Helper
    

    剃刀(_Layout)

    @Html.RenderScripts
    

    【讨论】:

      【解决方案2】:

      为什么不使用named sections 来定义要在每个局部视图中呈现的JavaScript?感觉就像您正在尝试复制这个已经存在的功能。

      设置您希望脚本在布局中呈现的位置。然后您可以选择在每个局部视图中指定其他脚本。

      主视图/布局

      <body>
      ...
        <script type="text/javascript" src="@Url.Content("/Scripts/GlobalScript.js")">
        @RenderSection("Javascript", required: false)
      </body>
      

      局部视图

      @section Javascript
      {
        <script type="text/javascript" src="@Url.Content("/Scripts/ScriptRequiredByThisPartial.js")"></script>
      }
      

      【讨论】:

      • Partials 不能使用section,这就是这段代码的目的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2019-09-29
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多