1

I am a compelte Knowbie so excuse my quesstion if it comes across dumb, i have created a small web application at the folliwng https://wireme.co.uk/BookList but i can not get the date to display correctly, not sure what i am doing wrong, please see my code below:

using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;


    namespace BookListRazor.Model
    {
        public class Book
        {
            [Key]
            public int PO { get; set; }
            [Required]
            public string Creator { get; set; }
            [Required]
            public string Company { get; set; }
    
            [DataType(DataType.Date)]
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy")]
            public DateTime Date { get { return Mydate; } set { Mydate = value; } }
    
            [DataType(DataType.Date)]
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy")]
    
            public DateTime Mydate = DateAndTime.Now;
            [DataType(DataType.Date)]
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy")]
            public DateTime MyDate { get; set; }
            
    
    
    
        }
    
    
    }
jbcom41
  • 57
  • 1
  • 6
  • 3
    *perhaps* this has to do with missing closing curly bracket `}` in date format – Cid Aug 04 '20 at 11:40

1 Answers1

2

You can use string to display it :

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public string MyDate { get; set; }

You can convert DateTime to string using Book's class constructor :

     public Book()
      {
        this.MyDate = Mydate.ToString();
      }

I would also change DateAndTime to DateTime as long as you declare using c# :

    public DateTime Mydate = DateTime.Now;

OR

What I would do is reducing amount of properties. If I understand correctly what you want to achive, this should be enough :

        public class Book
        {
            [Key]
            public int PO { get; set; }
            [Required]
            public string Creator { get; set; }
            [Required]
            public string Company { get; set; }
            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
            public string MyDate { get { return DateTime.Now.ToString(); } set { } }

        }
mike
  • 1,202
  • 1
  • 7
  • 20
  • Hi Mike, tried that but getting the following error "InvalidCastException: Unable to cast object of type 'System.DateTime' to type 'System.String'.." - any ideas?? – jbcom41 Aug 04 '20 at 16:07
  • The reason of an error was that are declyring ruturn value as a Date and since an udpate you return string. – mike Aug 05 '20 at 07:26