Original: 2 ways to format MVC dates
Suppose you have a class that contains a datetime type attribute, how do you make jointime appear in the format we expect when editing?
using System; using System.ComponentModel.DataAnnotations; namespace mvcapplication1.models{ publicclass Employee { public getset;}} }
In the HomeController:
using System; using SYSTEM.WEB.MVC; using Mvcapplication1.models; namespace mvcapplication1.controllers{ Public public ActionResult Index () { return View (new Employee () {jointime = DateTime.Now}); } }}
In the home/index.cshtml strongly typed view:
@model mvcapplication1.models.employee@{ "Index"; " ~/views/shared/_layout.cshtml " ;} = model. Jointime)
Mode 1: By encoding
Create a datetime.cshtml strongly typed partial view under Views/shared/editortemplates, formatted with ToString ():
@model DateTime? @Html. TextBox ("", Model.hasvalue? Model.Value.ToString ("yyyy-mm-dd"""new"date "})
Mode 2: by ViewData.TemplateInfo.FormattedModelValue
When we put [DisplayFormat (dataformatstring = "{0:YYYY-MM-DD}" ...] property is hit on the DateTime type property, we can get the display of the Type property formatted by ViewData.TemplateInfo.FormattedModelValue on the View page.
usingSystem;usingSystem.ComponentModel.DataAnnotations;namespacemvcapplication1.models{ Public classEmployee {[DisplayFormat (dataformatstring="{0:YYYY-MM-DD}", Applyformatineditmode =true)] PublicDatetime? Jointime {Get;Set; } }}
The datetime.cshtml strongly typed partial view is created under Views/shared/editortemplates, and the properties of the date type are formatted by ViewData.TemplateInfo.FormattedModelValue.
@model DateTime? @Html. TextBox ("" ""new {@class ="date"})