简体   繁体   English

jQuery的MVC日期时间选择器设置值未绑定到模型

[英]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. 我有绑定到我的视图模型上的datetime属性的日期时间选择器。 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. 当我从日期时间选择器中选择日期并回发时,它将值绑定到模型,但是当我尝试通过jequery设置值时,该值始终为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 javascript代码是

$("#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. 当我在浏览器中检查控制台时,我看到该值设置正确,但是当我发布表单并检查model属性时,该值为null。

I appreciate any help on this 我对此表示感谢

disabled HTML attribute prevents the input value to be submitted during POST request (treated as null value), as given by this explanation: 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. 如果是表单元素,则不会提交。

If you want to retain the value to be submitted during POST but prevents user to change its content, use HTML readonly attribute instead: 如果要保留要在POST期间提交的值,但又阻止用户更改其内容,请改用HTML readonly属性

$(':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: 另外,您需要将属性名称与在helper方法中分配的名称进行匹配:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM