Sravan
Sravan

Reputation: 1135

How to format the DateTime Property using MVC3 Razor?

I am having the following Razor Code to Render TextBox for ValidFrom Property of DateTime type.

@Html.TextBox("ValidFrom", (Model.ValidFrom.ToString("dd-MMM-yyyy")), new { @class = "FrmTextBox" })

And the same is rendering the Default Date(01-01-0001 00:00:00) as '01-Jan-0001' while opening of my Form and my values are also getting stored into the database once I submitted the form.

But, If I try to update the ValidFrom Property of the Subjected Record from the Database then the Record returning as 02-10-2012 00:00:00 but the Date is being displayed in the 02/10/2012 00:00:00 format only.

How to format the above DateTime Value into 02-Oct-2012.?

Could anyone please help..

Thanks in Advance.

Upvotes: 3

Views: 942

Answers (1)

Alexey Bychkov
Alexey Bychkov

Reputation: 581

Try to use the following attribute in your model.

 [DisplayFormat(ApplyFormatInEditMode = true, 
 DataFormatString = "specify_format_string_here")]

Then, on your view : @Html.EditorFor(m => m.ValidFrom). More about editor templates you can find for example here. For your requirements format string should be smth like this:

"{0:dd-MMMM-yyyy}"

Upvotes: 4

Related Questions