Suppose there is such a class that contains the DateTime type attribute. How can we make JoinTime display as the expected format during editing?
using System;using System.ComponentModel.DataAnnotations;namespace MvcApplication1.Models{ public class Employee { public DateTime? JoinTime { get; set; } }}
In 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}); } }}
In the Home/Index. cshtml strong type View:
@model MvcApplication1.Models.Employee@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml";}
Method 1: Encoding
In Views/Shared/EditorTemplates, create the DateTime. cshtml strongly-typed partial view and format it using ToString:
@model DateTime?@Html.TextBox("", Model.HasValue ? Model.Value.ToString("yyyy-MM-dd") : "", new {@class = "date"})
Method 2: Use ViewData. TemplateInfo. FormattedModelValue
When [DisplayFormat (DataFormatString = "{0: yyyy-MM-dd}"...] when the attribute is set to a DateTime type attribute, we can use ViewData on the view page. templateInfo. formattedModelValue gets the formatted display of this type of attribute.
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; } }}
In Views/Shared/EditorTemplates, create the DateTime. cshtml forced-type partial view and format the attributes of the date type through ViewData. TemplateInfo. FormattedModelValue.
@model DateTime?@Html.TextBox("", Model.HasValue ? @ViewData.TemplateInfo.FormattedModelValue : "", new {@class="date"})