Masriyah
Masriyah

Reputation: 2525

DateTime Value to null

Hey, This is kind of tough to explain because i don't even know how it is happening. I have a datepicker box which when the page is loaded that date box is set to null. Once the user chooses a date and clicks the submit button - the page is reloading and working as it should fine but a time format of zeros appears with the date like so :

5/11/2011 00:00:00

Is there a way i can get rid of the zeros in my post or get methods or any way possible?

Here is how my code looks like in the aspx page:

Begin Date: <%:Html.EditorFor(b => b.BeginDate)%><%:Html.ValidationMessageFor(b => b.BeginDate)%>

End Date: <%:Html.EditorFor(e => e.EndDate)%><%:Html.ValidationMessageFor(e => e.EndDate)%>

My ViewModel:

public DateTime? BeginDate { get; set; }

public DateTime? EndDate { get; set; }

This is based off of Darin's Answer:

in the ViewModel:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString ="{0:dd/MM/yyyy}")]
    public DateTime? BeginDate { get; set; }

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? EndDate { get; set; }

And in my .aspx page :

Begin Date: <%:Html.EditorFor(b => b.BeginDate)%><%:Html.ValidationMessageFor(b => b.BeginDate)%>

End Date: <%:Html.EditorFor(e => e.EndDate)%><%:Html.ValidationMessageFor(e => e.EndDate)%>

Upvotes: 0

Views: 1199

Answers (2)

Masriyah
Masriyah

Reputation: 2525

I was actually able to control it in my report file. in my .rdlc file i created an expression in the box i will show my date to the following:

DateValue(Parameters!BeginDate.Value)

and that eliminated the zeros from appearing in my text box as well.

thanks for everyone's help

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You could use the DisplayFormat attribute on your view model:

public class MyViewModel
{
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime Date { get; set; }
}

and in your view you would generate the corresponding input field using the EditorFor helper:

@Html.EditorFor(x => x.Date)

Now you could attach a datepicker to the resulting input using the same format and when the form is submitted it will keep the same format for the date field.

Upvotes: 1

Related Questions