Donate

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:
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
ASP.NET MVC String.Format() Not Showing Correct Format In Views Using jQuery Calendar

Correct Format With jQuery Datepicker
ASP.NET MVC String.Format() Not Showing Correct Format In Views Using jQuery Calendar

Greg Esguerra

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations