2012-11-27 1 views
6

Sto lavorando a un progetto ASPNET MVC 4 con jqgrid.Ordine di script Jquery nell'applicazione ASPNET MVC 4

Lì, ASPNET MVC 4 mette per default

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

nel file _Layout.cshtml alla fine di esso.

Ora, ho un Index.cshtml che utilizza jqGrid come

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

quindi devo includere script jqGrid come

@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> 
} 

Ma prima di usare qualsiasi cosa con .jqgrid ho bisogno di script jqGrid caricato che a sua volta ha bisogno di script jquery caricati, quindi, gli script jquery devono essere in cima invece che alla fine sul file _Layout.cshtml.

Secondo le best practice, gli script jquery devono essere caricati alla fine del file, ma se lo faccio, nel file Index.cshtml non sa cosa sia jQuery.

Non riesco a mettere gli script jqquery e sotto gli script jqgrid nella parte inferiore del file _Layout.cshtml visto sopra che è il contenuto del file Index.cshtml che utilizza gli script jqgrid.

C'è qualcosa che mi manca per poter mettere jQuery alla fine e poter ancora usare qualcosa con jquery nella vista?

Grazie! Guillermo.

risposta

13

__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> 
} 

Ma la migliore pratica sarebbe quella di avere un file JavaScript separato con il codice, in questo modo:

__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({ ... }); 

}); 
2

Ho riscontrato anche questo problema. Sembra un po 'controproducente non raggruppare jQuery in sé, ma è ciò che deve essere fatto. Lanciare un riferimento allo script jQuery nell'intestazione. Se imposti l'attributo src dello script jQuery a quello dell'istanza con privilegi di google-hosted, c'è un'alta probabilità che lo script sia già memorizzato nella cache del tuo client comunque.

Here is a nice reference...