Junior
Junior

Reputation: 11990

How can capture Month/Year in an Asp.Net MVC?

I have to capture DateTime with the following format MM/yyyy. My view-model looks like this

public class SomeViewModel
{
    public string Name { get; set; }

    [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? TargetMonth { get; set; }
}

Then I have razor's editor-template called Date.cshtml with the following code

@model DateTime?
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "form-control", placeholder = ViewData.ModelMetadata.Watermark })

When I select/type value like this 07/2018 I get the following error during the client-side validation

The field Target Month must be a date.

How can I correctly capture the month using the MM/yyyy format?

Upvotes: 0

Views: 2812

Answers (2)

sanfalero
sanfalero

Reputation: 382

I've replicated your issue on a sample project. The problem is that the DisplayFormat attribute is ignored in TextBox helpers (source).

I would recommend going for an existing datepicker library, there are plenty of good solutions to choose from. I've found a JS Fiddle using Bootstrap Datepicker that addresses your Month picker requirement.

Html:

<input type="text" class="monthPicker" placeholder="CheckIn" >

JS:

$('.monthPicker').datepicker({
    autoclose: true,
    minViewMode: 1,
    format: 'mm/yyyy'
})

You can change your editor template to use this datepicker.

Upvotes: 2

Byron Jones
Byron Jones

Reputation: 745

You'll want the 'TargetMonth' property on your view model to be a string, not a date. Validate the string to match this regular expression: '[0-1]?[1-9]/[1-2][0-9]{3}'

Then either add a get only property to your data model that parses the string and returns a DateTime instance, or do the conversion logic when you pass the value to its corresponding entity object for storage.

Upvotes: 0

Related Questions