My model has a object which has a date property…
[Required(ErrorMessage="{0} is required")]
[Display(Name="Donation date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DonationDate { get; set; }
The view has an editor for it….
<div class="editor-label">
@Html.LabelFor(model => model.Donation.DonationDate)
</div>
<div class="editor-field">
@Html.TextBox("txtDate", Model.Donation.DonationDate.ToString("dd/MM/yyyy"), new { @class = "date" })
@Html.ValidationMessageFor(model => model.Donation.DonationDate)
</div>
The controller just receives back the model… but when I do this in the controller and give it to another view…
ViewBag.Date = model.Donation.DonationDate;
Every time I just get back
1/1/0001 12:00:00 AM no matter what the date was set to. Any thoughts? Thanks!
Forgot to mention… I’m also using JQuery datepicker on the editor field:
$('.date').attr("placeholder", "dd/mm/yy").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true
});
You can use TextBoxFor so that the view engine knows how to label the form field appropriately (so that the model binder will recognize it on postback):
Alternatively, you could name the textbox correctly manually. I’m not sure exactly what that would look like …
Update
Ok, I as curious so I checked. The naming convention for nested fields uses the dot notation. So you should be able to write this:
Update #2
To format the correctly, apply an attribute to the DonationDate property in your model:
For this to work, you also have to use @Html.EditorFor instead of TextBoxFor.