jquery - where to add jQueryUI scripts in MVC page -
i'm using editortemplates folder, , following datetime.cshtml add date picker (jquery ui) datetime fields:
@model nullable<system.datetime> @if ( model.hasvalue ) { @html.textbox( "" , string.format( "{0:yyyy-mm-dd hh:mm}" , model.value ) , new { @class = "textbox" , @style = "width:400px;" } ) } else { @html.textbox( "" , string.format( "{0:yyyy-mm-dd hh:mm}" , datetime.now ) , new { @class = "textbox" , @style = "width:400px;" } ) } @{ string name = viewdata.templateinfo.htmlfieldprefix; string id = name.replace( ".", "_" ); } <script type="text/javascript"> $(document).ready(function () { alert("adding date picker"); $("#@id").datepicker ({ dateformat: 'dd/mm/yy', showstatus: true, showweeks: true, highlightweek: true, numberofmonths: 1, showanim: "scale", showoptions: { origin: ["top", "left"] } }); }); </script>
however, if add jquery scripts etc bottom of page, suggested best practice - above code, appears inline - above jquery scripts - , therefore doesn't run:
main cshtml razor view:
@renderbody() <hr> <footer> <p>© company @system.datetime.now.tostring("yyyy")</p> </footer> </div> @scripts.render("~/js") @scripts.render("~/jqueryui") @rendersection("scripts", required: false) </body>
should bypass best practice , add jquery scripts top of page - or there simpler way of making work, while still following best practice?
thank you,
mark
you should not have scripts in views or partials. scripts should placed belong - in separate javascript files.
so have javascript file enables datepickers, example ~/scripts/myscript.js
:
$('.datepicker').datepicker({ dateformat: 'dd/mm/yy', showstatus: true, showweeks: true, highlightweek: true, numberofmonths: 1, showanim: "scale", showoptions: { origin: ["top", "left"] } });
as can see have used class selector here: $('.datepicker')
in order attach datepicker plugin input fields have class="datepicker"
.
and that's left override scripts custom section in view (not in partials or templates):
@section scripts { <script type="text/javascript" src="~/scripts/myscript.js"></script> }
now template contain templates should contain - markup:
@model datetime? @html.textbox( "", string.format("{0:yyyy-mm-dd hh:mm}", model ?? datetime.now), new { @class = "textbox datepicker", @style = "width:400px;" } )
you might notice simplification of code.
and since followed best practices have scripts in separate files have bundle them:
@section scripts { @scripts.render("~/datepickers") }
or include in of bundles in layout gets minified , cached them , available pages.