3

This is my _Layout.cshtml

<html>
    <head>
        @RenderSection("Script", false)
    </head>
    ...
</html>

This is a simple edit page edit.cshtml

@model Shop.Models.Product
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.EditorForModel()

and this is ~/Views/Shared/EditorTemplates/Product.cshtml

@model Shop.Models.Product
@section Script {
    <script>alert("hello");</script>
}
...

@section Script{...} does not work in Product.cshtml because of EditorForModel. How can do it?

Ghooti Farangi
  • 19,926
  • 15
  • 46
  • 61
  • Just put the `@section Script{...}` into the `edit.cshtml` and every other View from where you use `Product.cshtml`. – nemesv May 30 '12 at 05:32
  • @nemesv I know it but I need a solution to use `@section Script{...}` in Product.cshtml – Ghooti Farangi May 30 '12 at 05:38
  • It won't work. `@section` is only allowed in layouts and regular views, so it's not supported in partial-views, editor or display templates. I think you can restructure your js in way that it won't be required to included from the `Product.cshtml`... – nemesv May 30 '12 at 05:46
  • possible duplicate of [Using sections in Editor/Display templates](http://stackoverflow.com/questions/5433531/using-sections-in-editor-display-templates) – juFo Apr 09 '14 at 13:41

1 Answers1

4

Sections work only in views, not in partials. An editor template is a special kind of partial. It's bad practice to put javascript in partials anyway, so I would simply declare the section in the Edit.cshtml view.

But if you very much insist on putting your scripts in the middle of your markup, since Razor doesn't support sections in partials, you could implement custom helpers to achieve that.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928