假設有這樣的一個類,包含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"})
