从控制器加载时,日期选择器不起作用

时间:2019-01-24 08:03:07

标签: asp.net-mvc datepicker jquery-ui-datepicker bootstrap-datepicker

我想问一下为什么从控制器加载模型后,我的日期选择器为何在我的模式中停止工作。

控制器:

public ActionResult LoadUserDetails(int userId){
   return PartialView("_EditUserDetailsModal", model);
}

查看:

$("#EditUserModalContent").html(response);

日期选择器:

// Settings for DataPicker
var currentYear = (new Date).getFullYear();
var maxDate = new Date();
maxDate.setFullYear(currentYear - 18);

$(".datepicker").datepicker({
     dateFormat: 'mm/dd/yy',
     changeMonth: true,
     changeYear: true,
     yearRange: '-100:-18',
     maxDate: maxDate,
     minDate: new Date((currentYear - 100), 12, 1)
});

型号:

[Display(Name = "User_DateOfBirth", ResourceType =typeof(Resources.Translation))]
[DataType(DataType.DateTime, ErrorMessageResourceType =typeof(Resources.Translation), ErrorMessageResourceName ="Global_ErrorMessageValidDate")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
public DateTime? DateOfBirth { get; set; }

当我不从控制器加载数据时(当我忽略以下行时,它会完美工作:

$("#EditUserModalContent").html(response))

请,我该如何解决?

1 个答案:

答案 0 :(得分:0)

模式选择器中的日期选择器吗?如果是,则$("#EditUserModalContent").html(response);删除了原始的日期选择器。需要重新初始化datepicker,因为已经运行的javascript代码仅适用于调用时页面上的.datepicker

$.ajax({ 
    url: '',
    ....
    success: function(response) {
        // response removes the initial datepicker
        $("#EditUserModalContent").html(response);
        // initialize the new datepicker input from the server
        var currentYear = (new Date).getFullYear();
        var maxDate = new Date();
        maxDate.setFullYear(currentYear - 18);
        $(".datepicker").datepicker({
            dateFormat: 'mm/dd/yy',
            changeMonth: true,
            changeYear: true,
            yearRange: '-100:-18',
            maxDate: maxDate,
            minDate: new Date((currentYear - 100), 12, 1)
        });
    }
})

编辑:在代码中添加了用于在ajax响应之后初始化datepicker