MVC日期格式化的2种方式

时间:2021-02-02 16:46:43

原文:MVC日期格式化的2种方式

假设有这样的一个类,包含DateTime类型属性,在编辑的时候,如何使JoinTime显示成我们期望的格式呢?

using System;
using System.ComponentModel.DataAnnotations; namespace MvcApplication1.Models
{
public class Employee
{
public DateTime? JoinTime { get; set; }
}
}

在HomeController中:

using System;
using System.Web.Mvc;
using MvcApplication1.Models; namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new Employee(){JoinTime = DateTime.Now});
} }
}

在Home/Index.cshtml强类型视图中:

@model MvcApplication1.Models.Employee

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
} <h2>Index</h2> @Html.EditorFor(model => model.JoinTime)

方式1:通过编码

在Views/Shared/EditorTemplates下创建DateTime.cshtml强类型部分视图,通过ToString()格式化:

@model DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("yyyy-MM-dd") : "", new {@class = "date"})

方式2:通过ViewData.TemplateInfo.FormattedModelValue

当我们把 [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}"...]属性打在DateTime类型属性上的时候,我们可以在视图页通过ViewData.TemplateInfo.FormattedModelValue获取该类型属性格式化的显示。

using System;
using System.ComponentModel.DataAnnotations; namespace MvcApplication1.Models
{
public class Employee
{
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? JoinTime { get; set; }
}
}

在Views/Shared/EditorTemplates下创建DateTime.cshtml强类型部分视图,通过ViewData.TemplateInfo.FormattedModelValue格式化日期类型的属性。

@model DateTime?
@Html.TextBox("", Model.HasValue ? @ViewData.TemplateInfo.FormattedModelValue : "", new {@class="date"})