Reputation: 1165
I have this problem, where i have 2 properties in my project entity:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "dd/MM/yyyy", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
[DisplayFormat(DataFormatString = "dd/MM/yyyy", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
In my view i have the following code.
<div class="control-group">
<label class="control-label" for="prependedInput">@Resources.Project.StartDate</label>
<div class="controls">
<div class="input-prepend">
<input type="text" name="StartDate" class="input-small datepicker" value="@DateTime.Now.ToDateFormat()" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="prependedInput">@Resources.Project.EndDate</label>
<div class="controls">
<div class="input-prepend">
<input type="text" name="EndDate" class="input-small datepicker" value="@DateTime.Now.ToDateFormat()" />
</div>
</div>
</div>
In my controller i am trying to create a new object but the ModelState.IsValid always returns false because the StartDate has a null value.
public virtual ActionResult Create(Project model)
{
if (ModelState.IsValid)
{
Repository.Project.Add(model);
return RedirectToAction(MVC.Project.Index());
}
return View(model);
}
How can i solve this problem and set the value of my nullable StartDate property to the date selected with datepicker ?
Upvotes: 3
Views: 699
Reputation: 9755
DisplayFormat
attribute have no effect on DateTime?
when binding data. Because of this default data binder expects the date to be in standard format f.e. YYYY-MM-dd
.
If you want to bind datetime in diffent format use custom data binder. You can find solution here:
http://blog.greatrexpectations.com/2013/01/10/custom-date-formats-and-the-mvc-model-binder/
It should work perfectly for your problem.
Upvotes: 3