This is the code which I have in my partial view
@model Contoso.MvcApplication.Models.Exercises.AbsoluteArithmetic
@using(Html.BeginForm())
{
This worked for me allowing me to colocate JavaScript and HTML for partial view in same file for ease of readability
In View which uses Partial View called "_MyPartialView.cshtml"
<div>
@Html.Partial("_MyPartialView",< model for partial view>,
new ViewDataDictionary { { "Region", "HTMLSection" } } })
</div>
@section scripts{
@Html.Partial("_MyPartialView",<model for partial view>,
new ViewDataDictionary { { "Region", "ScriptSection" } })
}
In Partial View file
@model SomeType
@{
var region = ViewData["Region"] as string;
}
@if (region == "HTMLSection")
{
}
@if (region == "ScriptSection")
{
<script type="text/javascript">
</script">
}
Check out my answer How to render a Section in a Partial View, which allows you to define Scripts and Styles in any view/partial view. It also takes care of duplicate includes.
My personal take is that sections aren't a good solution for styles and javascript includes.
Noob trick: Define a function in an already loaded file, and call the function on partial view load.
1.Have a separate js file that you load with your usual bundle:
bundles.Add(new ScriptBundle("~/bundles/CustomScripts").Include(
"~/Scripts/Custom/partial-view.js"
));
@Scripts.Render("~/bundles/CustomScripts");
function OnPartialViewLoad() {
// ... your onLoad work
}
<script type="text/javascript">
$(document).ready(function(){
OnPartialViewLoad();
});
</script>