2 ways to format MVC dates

Source: Internet
Author: User

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"})

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.