Tuesday, February 5, 2013

ASP.NET MVC String.Format() not showing correct format in Views using jQuery Calendar

Greetings,

Formatting display output of dates in asp.net mvc should work using String.Format() with custom date formatting criteria. However, applying String.Format() in asp.net ascx view does not display the desired format that I want. Example markup:
 <%: Html.TextBoxFor(model => model.HireDate, String.Format("{0:g}", Model.HireDate))%>  
Given Date Input: 2/6/2013 12:00:00 AM
Desired Output should be with time portion removed: 2/6/2013

Solution:
The trick to display the desired format was to decorate a display format attribute in my model class HireDate property:
Code:
     private DateTime hDay;  
     [DisplayName("Hire Date")]  
     [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]  
     public DateTime HireDate  
     {  
       get  
       {  
         if (hDay == DateTime.MinValue)  
         {  
           return DateTime.Today;  
         }  
         else  
           return hDay;  
       }  
       set  
       {  
         if (value == DateTime.MinValue)  
         {  
           hDay = DateTime.Now;  
         }  
       }  
     }
And in your .ascx view, use EditFor() instead of TextBoxFor()
 <%: Html.EditorFor(model => model.HireDate, Model.HireDate)%>  
Incorrect Format with jQuery datepicker

Correct Format with jQuery datepicker


Greg

0 comments:

Post a Comment