Jeandre Pentz
Jeandre Pentz

Reputation: 1002

ASP MVC Define Section in Partial View

As the title states, I want to define a section in a partial view.

My code that I've tested with are as follows:

Controller:

public ActionResult Test()
{
    return View();
}

public ActionResult PartialTest()
{
    return PartialView("_PartialTest");
}

Test.cshtml:

@{
    ViewBag.Title = "Test";
}

<h2>Test</h2>

@Html.Action("PartialTest")

_PartialTest.cshtml:

<p>partial Test</p>

@section scripts {
    <script type="text/javascript">
        $(document).ready(function() {
            alert("Test");
         });
     </script>
}

Placing the section scripts in the Test.cshtml works fine so the problem isn't in the layout.

Anyone know how to do this?

Upvotes: 28

Views: 47976

Answers (2)

keenns
keenns

Reputation: 903

I know this question is super out-dated, but for anyone out there who might still wondering (as I was):

You can actually get around this problem by changing the @section scripts { } portion in your partial views to this:

@using (Html.BeginScriptContext())
{
    Html.AddScriptBlock(
        @<script type="text/javascript">
        //rest of script
    );
}

This will allow you to have a script in your partial view and achieve that widget-like structure. Hope this helps!

Upvotes: 6

Henk Mollema
Henk Mollema

Reputation: 46641

Partial views don't support @section tag. You should add them in the view which references the partial view. See this question for more information: Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine.

It basically comes down to the fact that the main view referencing a partial should be responsible for including Javascript, not the partial view itself.

Upvotes: 41

Related Questions