Date issue in ASP.NET Core MVC: when I use type = month in input code not working

324 Views Asked by At

I am creating a monthly sales report. So in date input, I need only month and year, no need for the day. I used type month in input.

This is my view:

<div class="form-group">
    <label for="Date">Date</label>
    <input type="month" class="form-control" name="Date" id="Date" />
</div>
                        

I need to compare this date with my date in model:

public DateTime Entrydate { get; set; }

In the controller, for comparing the date in input and entry date

private IEnumerable<Sale>GetFilteredData(IEnumerable<Sale>  DateTime? Date)
{
    if (Date != null || Date != default(DateTime))
    {
        result = result.Where(a => a.Entrydate >= Date);
    }
}

It worked when I use type = date in my input, but when I use month, it is not working. What changes do I need to do to solve this problem?

1

There are 1 best solutions below

0
Mr.F.K On

you can use datepicker for select only month and year. datepicker needs some libraries like this

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />    
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet" />  

after you can write datepicker for entry input

  <script>
    $(function () {
        $('#datepicker').datepicker({
            format: 'mm/yyyy',
            startView: "months",
            minViewMode: "months",
            language: "tr"
        });
    });        
</script>

your input must be like

<div class="form-group">
   <div class='input-group date datepicker' id='datepicker'>
      <input type='text' class="form-control" asp-for="MyProperty" />
      <span class="input-group-addon">
         <span class="glyphicon glyphicon-calendar"></span>
      </span>
   </div>
</div>

model property

[DisplayFormat(DataFormatString = "{0:MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime MyProperty { get; set; }