MVC日期格式化的2種方式

來源:互聯網
上載者:User

標籤:c   style   class   blog   code   java   

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.