Reputation: 16358
This answer by Darin Dimitrov is a great solution to putting javascript into partial views but have them render at a later time.
I've converted the HtmlHelper extensions to VB.NET but I don't know how to use them with 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.
Upvotes: 0
Views: 1060
Reputation: 6301
Why not use named sections to define what JavaScript you want rendered in each partial view? It feels like you are trying to replicate this functionality which already exists.
Setup where you want your script to be rendered in your layout. And then you can optionally specify additional scripts in each of your partial views.
Main View/Layout
<body>
...
<script type="text/javascript" src="@Url.Content("/Scripts/GlobalScript.js")">
@RenderSection("Javascript", required: false)
</body>
Partial View
@section Javascript
{
<script type="text/javascript" src="@Url.Content("/Scripts/ScriptRequiredByThisPartial.js")"></script>
}
Upvotes: 0
Reputation: 16358
OP here. I thought of one solution which is to use Razor Helpers.
Extensions
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
Razor (Partial)
@Html.Script(Javascript)
@Helper Javascript()
@<text>
alert("It works");
</text>
End Helper
Razor (_Layout)
@Html.RenderScripts
Upvotes: 1