Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery scripts order in ASPNET MVC 4 application

I'm working on an ASPNET MVC 4 project with jqgrid.

There, ASPNET MVC 4 puts by default

@Scripts.Render("~/bundles/jquery")

in _Layout.cshtml file at the end of it.

Now, I have a Index.cshtml which uses jqgrid like

<script type="text/javascript">
    jQuery("#ajaxGrid").jqGrid({

So I must include jqgrid scripts like

@section jqgridScripts
{
    <script src="@Url.Content("~/Scripts/jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jqgrid/js/jquery.jqGrid.min.js")" type="text/javascript"></script>
}

But before using anything with .jqgrid I need jqgrid scripts loaded which in turn needs jquery scripts loaded, thus, jquery scripts needs to be at the top instead of at the end on _Layout.cshtml file.

According to best practices jquery scripts needs to be loaded at the end of the file, but if I do that, in Index.cshtml file it doesn't know what jQuery is.

I can't put jqquery scripts and below jqgrid scripts at the bottom of _Layout.cshtml file since above that is the Index.cshtml file content which uses jqgrid scripts.

Is there something I'm missing in order to be able to put jQuery at then end and still be able to use something with jquery in the view?

Thanks! Guillermo.

like image 953
polonskyg Avatar asked Nov 27 '12 13:11

polonskyg


1 Answers

__Layout.cshtml:

@Scripts.Render("~/bundles/jquery")
@RenderSection("jqgridScripts", required: false);

@* for script in current page *@
@RenderSection("pageScripts", required: false);

Index.cshtml:

@section pageScripts
{
<script type="text/javascript">
    jQuery("#ajaxGrid").jqGrid({
    ... 
</script>
}

But the best practice would be to have a separate javascript file with your code, like this:

__Layout.cshtml:

@Scripts.Render("~/bundles/jquery")
@RenderSection("pageScripts", required: false);

Index.cshtml:

@section pageScripts
{
    <script src="@Url.Content("~/Scripts/jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jqgrid/js/jquery.jqGrid.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/Site/myscript.js")" type="text/javascript"></script>
}

myscript.js:

$(function() {

   jQuery("#ajaxGrid").jqGrid({ ... });

});
like image 165
andres descalzo Avatar answered Sep 20 '22 09:09

andres descalzo