您可以将 [DisplayFormat] 属性与 EditorFor/DisplayFor 助手一起使用来格式化数据。
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/mm/dd}")]
public DateTime StartDate { get; set; }
然后在视图中:
@Html.EditorFor(m => m.StartDate)
或者,您也可以考虑为您的“工作”域模型定义单独的 ViewModel。虽然这种方法会产生更多的代码,但它提供了更多的灵活性并被认为是良好的实践。这是示例代码:
public class Work
{
public DateTime StartDate {get;set;}
}
public class WorkViewModel
{
public WorkViewModel()
{
}
public string StartDate { get; set; }
public static WorkViewModel Map(Work domainModel)
{
return new WorkViewModel() {
//Apply your Date format logic
StartDate = domainModel.StartDate.ToString("yyyy/MM/dd")
};
}
}
在行动方法:
var works = db.Work.Where(a => a.StartDate == DateTime.Now).ToList();
var workViewModels = new List<WorkViewModel>(works.Count);
foreach (var work in works)
workViewModels.Add(WorkViewModel.Map(work));
return View(workViewModels);