datetimeasp.net-mvc-3razorhtml.textbox

MVC3 & Razor - Change DateTime String from "mm/dd/yyyy 12:00:00 AM" to "mm/dd/yyy" in a Textbox


I am trying to stop the Time from showing up in a Birthday Text Field that uses DateTime

My Code: (I'm using the Jquery DatePicker)

<label for="birthday">Birthday:</label>
            @Html.TextBox("birthday", (Model.Birthday.ToString()), new { @class = "datePicker" })

The Javascript:

$(document).ready(function () {
    $('.datePicker').datepicker({ showOn: 'both', buttonImage: "/content/images/calendar-red.gif" });
});

I have the Model setup for the date:

[DataType(DataType.Date)]
public DateTime? Birthday { get; set; }

Still the Text in the Text box displays:

"8/21/2010 12:00:00 AM"

I want Text in the Textbox to diplay as just:

"8/21/2010"

I have tried everything from:

@inherits System.Web.Mvc.WebViewPage<System.DateTime>

but wont let me do that since I am @using a model


Solution

  • I would use an editor template and data annotations on the view model to specify formatting which makes the views much cleaner:

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

    and then inside your view:

    <span class="datePicker">
        @Html.LabelFor(x => x.Birthday)
        @Html.EditorFor(x => x.Birthday)
    </span>
    

    and then adapt the selector because the textbox will no longer have the datePicker class:

    $('.datePicker :text').datepicker({ 
        showOn: 'both', 
        buttonImage: "/content/images/calendar-red.gif" 
    });