2

I'm attempting to render JavaScript from a Razor Partial Page into the bottom of a (layout) Page. In Including JavaScript at bottom of page, from Partial Views Becuzz specifies that using a @section {} might be helpful for this purpose, but such sections are not rendered from Partial Pages.

One could in theory circumvent the problem by rendering the section of JavaScript outside of the Partial Page, into the Page itself. However, this is not possible, given that I want to reference a html element inside the script, as follows:

@section ScriptTag
{
    <script type="text/javascript">
        var example = $('#@Html.FieldIdFor(m => m.ExampleProperty)').val();
    });
    </script>
}

@Html.TextBoxFor(m => m.ExampleProperty)

How can I make this work?

Community
  • 1
  • 1
David Walschots
  • 12,279
  • 5
  • 36
  • 59
  • You may be interested in checking out a blog post I wrote with an idea to address this - http://forloop.co.uk/blog/managing-scripts-for-razor-partial-views-and-templates-in-asp.net-mvc – Russ Cam Feb 22 '12 at 11:24
  • possible duplicate of [Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine](http://stackoverflow.com/questions/7556400/injecting-content-into-specific-sections-from-a-partial-view-asp-net-mvc-3-with) – tugberk Feb 22 '12 at 12:36
  • @RussCam: Thanks. I think combining the script block and external JS files might work, while keeping the JS provided in a string format to a minimum. – David Walschots Feb 23 '12 at 08:40
  • @tugberk: my need for using Model properties makes the answers in the question you refer to irrelevant to the question posed here. – David Walschots Feb 23 '12 at 08:42
  • @DavidWalschots - yes, I think it works better to put your script in external files as opposed to in strings in server-side method calls, if you can. – Russ Cam Feb 23 '12 at 09:30
  • for anyone coming to this later - there is a nuget package for handling this: http://nuget.org/packages/Forloop.HtmlHelpers/ – Russ Cam Jun 17 '13 at 20:21

1 Answers1

0

You can only call RenderSection between two Views/Layouts that are directly related.

In this situation you would need to essentially redefine and render the section in your View in the middle.

See: http://blogs.msdn.com/b/marcinon/archive/2010/12/15/razor-nested-layouts-and-redefined-sections.aspx for a clearer explanation

Simon West
  • 3,708
  • 1
  • 26
  • 28