OfficialNate
OfficialNate

Reputation: 21

MVC: ViewModel values will not display in datepicker using type="month"

Apologies if this has already been asked - I have been searching Google for an hour with no luck so figured I'd post here and see if I could get an answer.

I am building a web application using MVC 5 + Entity Framework. One of the modules that I am developing is a fuel card tracker which contains details about fuel cards attached to vehicles.

I have a basic view model called FuelCardViewModel which is the FuelCard model (from EF) with a few SelectList objects. One property I have is a DateTime property called ExpiryDate which will hold the expiry date of the card.

When I populate the view model and send it to the Edit view, all of the fields are automatically filled in using the values in the ViewModel except the ExpiryDate field. When this field is set to type = "date", the value is pulled through and displayed correctly, so I know this isn't an issue with my ViewModel binding. Problem is, I want month/year only, so I have to use type = "month". When it is set to type = "month" (to only display a month/year picker as per card expiry date formatting), the value does not display (although I can still see the value when I view the source and look at the value property. This further backs up the fact that the ViewModel binding is working correctly, but just the formatting is messed up when using a month picker instead of a normal date picker). Any help with this is much appreciated; if more info is required let me know and I can provide.

ExpiryDate property in FuelCardViewModel:

[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMMM yyyy}")]
[DataType(DataType.Date)]
[DisplayName("Expiry Date")]
public DateTime ExpiryDate { get; set; }

If I want to use type = "date", I have to change {0:MMMM yyyy} to {0:yyyy-MM-dd} as per other answers on here, so changing it to {0:MMMM yyyy} is just an attempt to fix the issue.

The field in my Edit view:

 <div class="form-group">
     @Html.LabelFor(model => model.ExpiryDate, htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
         @Html.EditorFor(model => model.ExpiryDate, new { htmlAttributes = new { @class = "form-control", type = "month"} })
         @Html.ValidationMessageFor(model => model.ExpiryDate, null, new { @class = "text-danger" })
     </div>
 </div>

How the Edit view displays (with type = "month"):

View Image

How the Edit view should display:

View Image

Upvotes: 1

Views: 406

Answers (1)

OfficialNate
OfficialNate

Reputation: 21

Finally solved this! Figured I would post the solution here to help those in need.

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMMM yyyy}")]

should look like this:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM}")]

Such a simple error but my problem is now solved!

Upvotes: 1

Related Questions