您现在的位置是:网站首页> 编程资料编程资料
ASP.NET MVC格式化日期_实用技巧_
2023-05-24
352人已围观
简介 ASP.NET MVC格式化日期_实用技巧_
假设有这样的一个类,包含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"; } Index
@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"})到此这篇关于ASP.NET MVC格式化日期的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。
您可能感兴趣的文章:
