ASP.net 2.5 & MVC2.0

hariaspind
hariaspind used Ask the Experts™
on
I have a Datetime property  as
       [DisplayName("*Active Date:")]
        [Required(ErrorMessage = "Please Enter Active Date.")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]    
        public DateTime ActiveDate { get; set; }

While opening the new screen to let the user to enter add a new record the date field always come with a "1/1/0001 12:00:00 AM" ,how to avoid that ?


Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Hi,
This is the problem of using automatic properties, when access a property the compiler will initialize it with a default value that is the reason you are getting 1/1/0001 12:00:00 AM when it is initially loaded.
In order to avoid this you can assign the current date as the default in one of the following way

1. In the constructor of the class assign a default value

     ActiveDate

Commented:
oops sorry accidentely submitted it
1. In the constructor of the class assign a default value

public yourclass ()
{
     ActiveDate = DateTime.Now;
}

2. you can have a DefaultValue attribute and decorate the property with that attribute. You can refer to the following article on how to do that
http://www.codeproject.com/KB/dotnet/AutoPropsDefaultValues.aspx

I hope that this helps you.

Thanks and regards,
venki

Author

Commented:
It's a good suggestion .But my user don't agree with it .
Commented:
I assume that you do not want to display a default date.
Then one workaround I think will work is make the property as nullable and in the constructor of your class set that property to null. So that by default you will receive a null and not the default date.

//property
public DateTime? ActiveDate { get; set; }


//constructor
    public YourClass()
    {
        ActiveDate = null;
    }

I hope that this helps you.

Thanks and regards,
Venki

Author

Commented:
Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial