来自 jquery 的 mvc 日期时间选择器设置值未绑定到模型

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

我有一个日期时间选择器,它绑定到我的视图模型上的日期时间 属性。 当我 select 来自日期时间选择器的日期和我 post 返回时,它将值绑定到模型,但是当我尝试通过 jequery 设置值时,该值始终为空。

我的模型是:

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

}

查看代码为

<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代码为

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

因此,当我单击选项按钮时,它会设置日期时间选择器的日期

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

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

当我在浏览器中检查控制台时,我发现该值设置正确,但是当我 post 表单并检查模型 属性 时,它为空。

感谢任何帮助

disabled HTML 属性阻止在 POST 请求期间提交输入值(被视为空值),如以下解释所示:

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.

如果您想保留在 POST 期间提交的值但阻止用户更改其内容,请改用 HTML readonly attribute

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

您还需要将 属性 名称与辅助方法中指定的名称相匹配:

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