我使用 EditorTemplates 文件夹和以下 DateTime.cshtml 将日期选择器 (jQuery UI) 添加到所有日期时间字段:
@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>
但是,如果我将 jQuery 脚本等添加到页面底部,正如建议的那样,现在是最佳实践 - 上面的代码显示为内联 - 位于 jQuery 脚本上方 - 因此不会运行:
CSHTML Razor 主视图:
@RenderBody()
<hr>
<footer>
<p>© Company @System.DateTime.Now.ToString("yyyy")</p>
</footer>
</div>
@Scripts.Render("~/js")
@Scripts.Render("~/jqueryui")
@RenderSection("Scripts", required: false)
</body>
我应该绕过最佳实践并将 jQuery 脚本添加到页面顶部 - 还是有更简单的方法来完成这项工作,同时仍然遵循最佳实践?
谢谢,
标记
最佳答案
您应该将其放在以下部分:
@section Scripts {
<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>
}
这样您的脚本将添加到 jQuery 声明下方
关于jquery - 在 MVC 页面中添加 jQueryUI 脚本的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16215912/