Asp.net mvc 具有默认日期的MVC4日期选择器
我正在使用MVC4和Razor视图引擎。我的控制器如下:Asp.net mvc 具有默认日期的MVC4日期选择器,asp.net-mvc,asp.net-mvc-4,razor,datepicker,Asp.net Mvc,Asp.net Mvc 4,Razor,Datepicker,我正在使用MVC4和Razor视图引擎。我的控制器如下: public ActionResult Index() { return View(new EmployeeIndexViewModel { ToDate = DateTime.Now }); } public class EmployeeIndexViewModel { [DataType(DataType.Date)] public DateTime ToDate {
public ActionResult Index()
{
return View(new EmployeeIndexViewModel
{
ToDate = DateTime.Now
});
}
public class EmployeeIndexViewModel
{
[DataType(DataType.Date)]
public DateTime ToDate { get; set; }
}
我的视图模型如下所示:
public ActionResult Index()
{
return View(new EmployeeIndexViewModel
{
ToDate = DateTime.Now
});
}
public class EmployeeIndexViewModel
{
[DataType(DataType.Date)]
public DateTime ToDate { get; set; }
}
在我看来,我有一个简单的EditorFor()
调用:
@Html.EditorFor(model => model.ToDate)
但仍然在我的日期选择器中获得默认(屏蔽)值:
问题:
如何将今天的日期(来自控制器)显示在此处?您应该从jQuery级别执行此操作:
$( ".selector" ).datepicker( "setDate", yourDate);
例如,如果要设置今天的日期:
$( ".selector" ).datepicker( "setDate", new Date());
您还可以尝试在视图模型类中添加DisplayFormat
属性,以确保日期选择器正确解释数据格式:
public class EmployeeIndexViewModel
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ToDate { get; set; }
}
我的问题不是我最初认为的jQuery或MVC4问题。这与兼容HTML5的浏览器如何显示日期选择器有关。我以错误的格式将日期传递给视图 我将ViewModel修改为此,现在日期已正确填充:
public class EmployeeIndexViewModel
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ToDate { get; set; }
}
U可以使用JQuery设置输入或type=“date”(datetimepicker)输入 在锐利的视野中 @TextBoxFor(m=>m.StartedDate,new{@id=“mydate”、@type=“date”、@class=“form control”}) 下面是JS代码
$(document).ready(function () {
var dateNewFormat, onlyDate, today = new Date();
dateNewFormat = today.getFullYear() + '-';
if (today.getMonth().length == 2) {
dateNewFormat += (today.getMonth() + 1);
}
else {
dateNewFormat += '0' + (today.getMonth() + 1);
}
onlyDate = today.getDate();
if (onlyDate.toString().length == 2) {
dateNewFormat += "-" + onlyDate;
}
else {
dateNewFormat += '-0' + onlyDate;
}
$('#mydate').val(dateNewFormat);
});
您将如何在.cshtml文件中反映此更改?请删除
.EditorFor()
调用并静态插入一个文本框好吗?首先尝试添加我建议的属性,这似乎是最简单的解决方案。我这样做了,日期选择器仍然显示在我问题的屏幕截图中。将编辑器更改为:@Html.EditorFor(model=>model.ToDate,new{id=“ToDate”});然后是$(“#toDate”).datepicker(“setDate”,new Date());问题不在于jQuery,而在于.EditorFor()
调用将type='date'
属性添加到HTML属性。我要指出的一点是,DataFormatString格式与实际显示的格式不同。如果要使用MM/dd/yyyy的DataFormatString,那么它将不起作用。无论日期的实际格式如何,似乎都必须使用yyyy-MM-dd。您在属性中传递了yyyy-MM-dd
,但我在您的照片中看到MM/dd/yyyy
。发生了什么事?我这样问是因为我想改变我眼中的顺序,但我在你的照片中看到了同样的问题。