The file "~/Views/Position/Edit.cshtml" cannot be requested directly because it calls the "RenderSection" method

Luis Valencia picture Luis Valencia · Oct 18, 2011 · Viewed 36k times · Source

I am trying to separate all the things that I could reuse in sections, so it would be easier for me to maintain.

However I got this exception: The file "~/Views/Position/Edit.cshtml" cannot be requested directly because it calls the "RenderSection" method

I created a file called sections.cshtml with the following content:

@section scripts{
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}

And in the _layout.cshtml file I changed it to:

<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    @RenderSection("scripts", required:false)
    @*<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>*@
</head>

When I go to the view in the browser and check the source code it shows only:

<head>
    <meta charset="utf-8" />
    <title>Edit</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
</head>

Answer

Martin Booth picture Martin Booth · Oct 18, 2011

RenderSection can only exist in Layout files (i.e. master pages)... its purpose is to allow the pages you can request directly to target various sections of a Layout (layout being a file common to all pages which choose to use it) and supply content for these different sections.

If you want to separate this section out as something which is resuable on many pages you should put it in a partial and replace the rendersection call to something like

@Html.Partial("Scripts")