I have checkbox option that after I check it, I change the value of an input field that shows only a Month and Year. In the case the checkbox is not selected. The user clicks on the input and a datepicker gives the option to choose the date(Month/Year). With the first option the values are not posted correctly, with the second yes. What I am doing wrong?
Unchecking year to Date and clicking on the input instead
Now if I check the (year to date) and post the value then startDate end endDate have a null value.
My Controller is as follow
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Index(ManualRecViewModel vm)
My ViewModel has field startDate and EndDate
public class ManualRecViewModel
{
public DateTime? startDate { get; set; }
public DateTime? endDate { get; set; }
}
and my View is
<div class="input-group">
<div>
@Html.CheckBox("year-to-date", false)
@Html.Label("Year to Date")
</div>
<div class="dates-filters">
<div>
@Html.Label("From:")
</div>
<div>
@Html.TextBoxFor(m => m.startDate, new { @readonly = "readonly" })
</div>
<div>
@Html.Label("To:")
</div>
<div>
@Html.TextBoxFor(m => m.endDate, new { @readonly = "readonly" })
</div>
</div>
</div>
I have a js that set the values to the input
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
$("#startDate").datepicker('setDate', new Date(year, 0, 1));
$("#endDate").datepicker('setDate', new Date(year, month, 1));
I've had this issue before and found that using the
$.trigger("change")
method is needed, because using set and$.val()
methods don't actually cause the input fields value to change for the form submission