0

I tried to place a script in a specified portion of a layout using @section inside a partial view. But it is not working.

_Layout.cshtml

<!DOCTYPE html>
<html lang="en">
<head>
@RenderSection("PageSpecificCSSFiles", false)
</head>
<body>
<div>@RenderBody()</div>
 <script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.js")"></script>
@RenderSection("PageSpecificJSFiles", false)
@RenderSection("PageSpecificJSScript", false)
</body>

DetailPage.cshtml

@{
    ViewBag.Title = "Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="tabs">
 @{ Html.RenderPartial("BasicDetails");}
</div>

Partial View BasicDetails.cshtml

<input id="dob" name="DateOfBirth" value="" />
@section PageSpecificJSScript{

<script type="text/javascript">

$(document).ready(function(){
   $('#dob').datepicker();
});

</script>

}

The datepicker has not configured because @section is not working.

Could any one tell how to achieve this in partial view? How can we force a script inside a partial views into a particular portion of a layout?

Note: I have added JS files at bottom in order to improve performance. I don't prefer moving it to top of the page.

Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120
  • Using css property and custom js on layout page, you can easily use date picker, aka do not repeat yourself. – AnandMohanAwasthi Feb 10 '13 at 15:26
  • @Murali, sadly, you cannot populate content section (in your _layout) from a child partial. During the render process, the Razor engine ONLY checks as far as the body of the rendered View and does not bother checking if any child partials contain a corresponding section. Sorry. – Dave Alperovich Feb 10 '13 at 16:34
  • @DaveA, i think it would check the Layout property here and failed to use, because of partial. let me try move all my scripts to top of page and run with out sections, then it will work fine. If i have scripts placed at bottom for better practice, my partial view scripts will say object undefined for $. Of course, it will throw :) – Murali Murugesan Feb 10 '13 at 16:42
  • @Murali, remember that sections are rendered by the Razor engine BEFORE they reach the browser. This means that JS does not run until _layout section -> View section mapping has already been performed. – Dave Alperovich Feb 10 '13 at 16:45
  • @DaveA, I think you are correct. In that case i think i need to place all my required files at top of page and remove sections in partial views. So when a partial view render a script blog it will work ok as the required dependency like jQuery are already referred in top. But nothing stop us to use a script in partial view i think – Murali Murugesan Feb 10 '13 at 16:48
  • @Murali, yes you are correct. JS injection is your best approach. I would suggest creating a div and performing something like $('#seciont').load(); – Dave Alperovich Feb 10 '13 at 16:50

0 Answers0