2013-07-26 81 views
0

This answer by Darin Dimitrov是一個很好的解決方案,可以將javascript放入部分視圖中,但在稍後時間渲染它們。如何將這個Razor代碼從C#轉換爲VB.NET?

我已將HtmlHelper擴展轉換爲VB.NET,但我不知道如何將它們與Razor一起使用。

Extension

@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.

回答

0

OP這裏。我想到了一個使用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 
0

爲什麼不使用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> 
} 
+0

局部模板不能使用的部分,這是該代碼的目的。 –