该应用程序位于ASP.NET MVC 4中,其中在“视图”中,将文本框附加到jQuery DatePicker,以仅选择“月份”和“年份”组合。
它声明为:
@Html.TextBox("myDate", Model.myDate.HasValue ? Model.myDate.Value.ToString("MM/dd/yyyy") : string.Empty, new { @readonly = "readonly", maxlength = "12", style = "width: 75px;height:20px", id = "myDate" })
值取为:
$(function () {
$("#myDate").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'MM yy',
minDate: 0,
onClose: function () {
var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
},
beforeShow: function () {
if ((selDate = $(this).val()).length > 0) {
iYear = selDate.substring(selDate.length - 4, selDate.length);
iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5),
$(this).datepicker('option', 'monthNames'));
$(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
}
}
});
});
文本框中的值通过ajax调用发送到控制器方法:
data: $("#myForm").serializeArray();
在此处在发送之前检查Array表单时,文本包含的值为“ 2019年9月”,“ 2019年7月”等。
在模型中,字段myDate被定义为数据类型DateTime?没有其他属性。
问题是,当我选择2019年9月时,代码隐藏端的基础模型将为空值。 最初我认为可能是因为9月有4个字符,但2019年6月,2019年7月可以正常工作。
我不确定为什么在其他月份工作时,仅对于包含Sept的myDate的值为空。
答案 0 :(得分:0)
所以终于找到了答案。 .net框架无法将2019年9月转换为有效的DateTime,但在经过2019年9月或2019年9月时运行良好。 要对已将monthNames数组作为参数传递给DatePicker的计数器进行计数,使其仅具有3个字母月份的名称;
$(function () {
$("#myDate").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'MM yy',
minDate: 0,
monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
onClose: function () {
var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
},
beforeShow: function () {
if ((selDate = $(this).val()).length > 0) {
iYear = selDate.substring(selDate.length - 4, selDate.length);
iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5),
$(this).datepicker('option', 'monthNames'));
$(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
}
}
});
});
此方法有效,现在我可以获得有效的DatetIme,日期为2019年9月