I have an ASP.NET MVC3 application in C# and Razor.
I use the standard _Layout.cshtml from the MVC3 application template in VS2010. I would like to add Javascript code in one of my Partial View just when the View is rendered and not attach the Javascript directly in the _Layout.
My View looks like this:
@model MyNameSpace.ViewModels.MyViewModel
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Filters</legend>
@{ Html.RenderPartial("Filters", Model.Filters); }
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
And my Partial View Filters.cshtml looks like this:
@model MyNameSpace.ViewModels.FiltersViewModel
<p>
@Html.DropDownListFor(
x => x.Type,
new SelectList(Model.Types, "Value", "Text"),
"-- select type --"
)
</p>
<p>
@Html.DropDownListFor(
x => x.Category,
new SelectList(Model.Categories, "Value", "Text"),
"-- select category --"
)</p>
<script type="text/javascript">
//Some Javascript
</script>
If I leave the View like this, the Javascript is rendered inside the <body> and it looks very ugly. I can add the Javascript directly in the <head> section of the _Layout but it is not what I want. How can I achieve my purpose?