如何删除mvc4文本框中的默认日期?

Nir*_*ole 3 c# asp.net-mvc asp.net-mvc-4

我在mvc4应用程序中有一个文本框,如下所示.

@Html.TextBoxFor(x=>x.dateofAction, ViewBag.filterdateTime as string,  new { @id = "dateofAction", @placeholder = "Date Of Action", @class = "txtBox form-control calender validate[required]" })
Run Code Online (Sandbox Code Playgroud)

我在这个文本框中使用jquery日历.

 $(document).on('focus', '.calender', function(){
         $(this).datepicker({

             dateFormat: "dd/mm/yy",
             changeMonth: true,
             changeYear: true,
             showOn: 'button',
             buttonImage: '/images/icondate.png',
             buttonImageOnly: true
        })
            });
Run Code Online (Sandbox Code Playgroud)

这是我的模特

 [DisplayName("dateofAction")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime dateofAction { get; set; }
Run Code Online (Sandbox Code Playgroud)

第一次页面加载默认日期1/1/0001 12:00:00 AM显示在文本框中时,我遇到问题.其实我想显示占位符值.

我可以知道为什么我无法获得占位符价值吗?

小智 6

要使用占位符显示空文本框,您需要使属性可以为空.如果还想要选择日期,那么您还可以使用该[Required]属性修饰属性.

另请注意,您的方法[DisplayFormat]是不必要的,并且会被该TextBoxFor()方法忽略.您还应该使用[Display]属性,而不是[DisplayName]您的属性

[Display(Name= "Date of Action")]
[Required(ErrorMessage = "Please select a date")]
public DateTime? dateofAction { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后在视图中你的代码应该是正确的

@Html.TextBoxFor(x=>x.dateofAction, new { @placeholder = "Date Of Action", @class = "txtBox form-control calender validate[required]" })
Run Code Online (Sandbox Code Playgroud)

并且你的datepicker插件应该在渲染DOM时初始化,而不是每次聚焦时

$('#dateofAction').datepicker({
    dateFormat: "dd/mm/yy",
    ....
})
Run Code Online (Sandbox Code Playgroud)