0

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

5
  • You have disabled the control - disabled controls do not post back a value Commented Sep 15, 2017 at 9:19
  • 2
    thDate.attr("disabled", 'disabled'); not submit value during POST - use thDate.attr("readonly", 'readonly'); instead. Commented Sep 15, 2017 at 9:20
  • Your TextBoxFor is binded on DDate whereas your model property name is Date ... Is this a typo ? Commented Sep 15, 2017 at 9:27
  • yes, actually its a typo Commented Sep 15, 2017 at 9:30
  • @TetsuyaYamamoto it worked, thank you very much. I've struggled with this allot. Commented Sep 15, 2017 at 9:35

1 Answer 1

1

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" })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.