Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 434
Luis Valencia Avatar asked Oct 18 '11 13:10

Luis Valencia


2 Answers

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")
like image 53
Martin Booth Avatar answered Oct 21 '22 22:10

Martin Booth


Alternatively you could use helper to separate code you use more often. Especially if you cannot use sections because of the constraint Martin-Booth mentioned.

@helper 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 the usage is just:

<somehtml />
@Scripts()
<somehtml />
like image 44
Gerwald Avatar answered Oct 21 '22 21:10

Gerwald