javascriptjqueryasp.net-mvcdatetimejquerydatetimepicker

mvc datetime picker setting value from jquery does not bind to model


I have date-time picker that is bound to a datetime property on my view-model. when I select the date from date-time picker and I post back, it binds the value to the model, but when I try to set the value through jequery, the value is always null.

my model is:

 public class viewmodel
{
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public datetime DDate { get; set; }

}

and the view code is

<div class="col-md-3">
@Html.TextBoxFor(m => m.DDate, new {@class = "form-control datepicker" })
@Html.ValidationMessageFor(model => model.DDate, "", new { @class = "text-danger" })</div>

javascript code is

$("#DDate").datepicker({ dateFormat: 'dd/mm/yy' });

so when I click an option button it sets the date of the datetime picker

$(':input[id="rbVatVoluntary"]').click(function () {

    var thDate = $("#DDate");
    thDate.attr("disabled", 'disabled');
    thDate.datepicker('setDate', new Date());});

When I check the console in the browser, I see that the value is set correctly but when I post the form and check the model property, it is null.

I appreciate any help on this


Solution

  • disabled HTML attribute prevents the input value to be submitted during POST request (treated as null value), as given by this explanation:

    Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted.

    If you want to retain the value to be submitted during POST but prevents user to change its content, use HTML readonly attribute instead:

    $(':input[id="rbVatVoluntary"]').click(function () {
        var thDate = $("#Date");
        thDate.attr("readonly", "readonly");
        thDate.datepicker('setDate', new Date());
    });
    

    Also you need to match the property name to assigned one in helper method:

    @Html.TextBoxFor(m => m.Date, new { @class = "form-control datepicker" })