简体   繁体   中英

Set value to input type=“date” from codebehind

I want to assign value to my HTML tag input type="date" from C# codebehind in ASP.NET web application. After page is loaded, the value is not visible, but in chrome dev tools i can see the value:

在此处输入图片说明

ASPX:

<input type="date" runat="server" id="date_datumPrispetja" value="dd. MM. yyyy" />

Codebehind:

string date = myDate.ToString("dd. MM. yyyy"); //value of date: "09. 04. 2017";
date_datumPrispetja.Value = date;

Is this is even possible, to assign value from codebehind to this HTML5 element?


EDIT:

Compare on datetime and date input type. C#:

date_datumPrispetja.Value = DateTime.Now.ToString("dd. MM. yyyy");
hi.Value = DateTime.Now.ToString("dd. MM. yyyy");

ASPX:

<input type="date"  runat="server" id="date_datumPrispetja" value="dd. MM. yyyy"/>
<br />
<input type="datetime" runat="server" id="hi" value="dd. MM. yyyy" />

RESULT:

在此处输入图片说明

I think it should be work, where did you put this code in:

string date = myDate.ToString("dd. MM. yyyy"); //value of date: "09. 04. 2017";
date_datumPrispetja.Value = date;

Page_Load()?

My test code as bellow:

protected void Page_Load(object sender, EventArgs e)
    {
        hi.Value = DateTime.Now.ToString("yyyy-MM-dd");
    }

Then it worked well.

这对我有用。

TextBox.Text = Convert.ToDateTime('01-01-2020').Date.ToString("yyyy-MM-dd");

Mobile Safari, Firefox and Chromium accept the date value only in format

<input type="date" value="2017-04-27">

and will print the date in the localized format. If they get a localized format as input (eg "27.04.2017") they print placeholders only.

However Safari accepts

<input type="date" value="27.04.2017">

On the other hand if Safari get the input format "2017-04-27", it will print this value in a non localized form.

Inside the browser's DOM the input value is stored attribute defaultValue (true for all browsers) and the attribute value is empty (not true for Safari).

My workaround for this confusion is some javascript:

 $(function () { var datefields = $('.TTMMJJ') for (i = 0; i < datefields.length; i++) { datefields[i].type = "date"; var defaultVal = datefields[i].defaultValue; var val = datefields[i].value; if (defaultVal.length > 0 && val.length == 0) { var darr = defaultVal.split("."); if (darr.length == 3) { var year = darr[2]; var month = darr[1]; var day = darr[0]; if (year.length == 2) { year = "20" + year; } var s = year + '-' + month.padStart(2,0) + '-' + day.padStart(2,0); datefields[i].value = s; } } } });

Note that

Date.parse("27.04.2017") 

works with Chromium but not with Firefox.

这对我有用:

txtFechaOtorgamiento.Text = Format(servicio.FechaOtorgamiento, "yyyy-MM-dd");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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