简体   繁体   English

将值从JQuery Datepicker传递到后面的代码

[英]Passing value from JQuery Datepicker to code behind

I am using JQuery Datepicker in my .aspx file. 我在.aspx文件中使用JQuery Datepicker。

I need to use the date value in my code behind file. 我需要在文件后面的代码中使用日期值。 This is my function which I want to update a hidden value on my page which I can use in my code behind. 这是我的功能,我想更新页面上的隐藏值,以便在后面的代码中使用。

$(function () {
    $("#datepicker").datepicker({ minDate: 0,
        onSelect: function () {
            var dueDate= document.getElementById('dueDate');
            dueDate.value = $(this).datepicker('getDate');
        }
    });
});

My hidden value which I want to update, which is on the same .aspx page: 我要更新的隐藏值,在同一.aspx页上:

<Input id="dueDate" type="hidden" runat="server" />

Now in my code behind, I want to use the date like so: 现在在我后面的代码中,我想像这样使用日期:

DateTime due= dueDate.Value;

This gives me an error: 这给我一个错误:

Cannot implicitly convert type 'string' to 'System.DateTime'    

I get the same error when I use 使用时出现相同的错误

DateTime due = Convert.ToDateTime(dueDate.Value);

What is the correct way to use the date from Datepicker in the code behind? 在后面的代码中使用Datepicker中的日期的正确方法是什么?

DateTime.Parse(...)

or 要么

DateTime.ParseExact(...)

or 要么

DateTime.Parse("01/01 2010");

or use 或使用

DateTime.TryParse

if you aren't sure it converts in which type every time, ie. 如果您不确定每次都会转换为哪种类型,即。 not always a date, so try this 4 and check 并非始终是日期,因此请尝试此4并检查

Provide a name for the datepicker 提供日期选择器的名称

<Input id="dueDate" name = "dueDate" type="hidden" runat="server" />

and use the below 并使用以下

String text = Page.Request.Form["dueDate"]

Consider having the following code on your .aspx file, removing runat server: 考虑在您的.aspx文件中包含以下代码,删除运行服务器:

<input type="hidden" id="dueDate" name="dueDate" value="" />

Now make the following change in your jquery datepicker function: 现在,在您的jquery datepicker函数中进行以下更改:

$(function () {
    $("#datepicker").datepicker({
        minDate: 0,
        dateFormat: "dd-mm-yyyy",
        onSelect: function() {
            $("#dueDate").val() = $(this).datepicker("getDate");
        }
    });
}

This way the hidden field value of dueDate gets updated whenever the value of your datepicker control is changed. 这样,只要更改datepicker控件的值,dueDate的隐藏字段值就会更新。 Further since your hidden field now has a name and value attribute associated with it, your code behind would receive its value as a string whenever your form is posted. 此外,由于您的隐藏字段现在具有与之关联的名称和值属性,因此,每当发布表单时,后面的代码都将以字符串形式接收其值。

Now in your code behind file, create your DateTime object as follows: 现在,在文件背后的代码中,如下所示创建DateTime对象:

string[] dueDateSplit = Request.Form["dueDate"].Split('-');
DateTime due = new DateTime(dueDateSplit[2], dueDateSplit[1], dueDateSplit[0]);

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

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