Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 817
Jeandre Pentz Avatar asked Jul 26 '13 08:07

Jeandre Pentz


People also ask

Can partial view have layout?

Yes, even in Partial View also we can set Layout property which turns Partial View as normal View with Layout .

How do you render a partial view inside a view in MVC?

Partial function which renders the Partial View. The name of the View and the object of the CustomerModel class are passed to the @Html. Partial function. In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.


1 Answers

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.

like image 190
Henk Mollema Avatar answered Sep 28 '22 01:09

Henk Mollema