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?
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.cshtmlview.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.