Selman
Selman

Reputation: 97

Set Input type=date

Thank you very much for your time

My question is How to set value input of type date?

@Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "form-control", @type = "date" } })

that it comes after Run

<input class="form-control text-box single-line" data-val="true" data-val-date="The field Date must be a date." data-val-required="The Date field is required." id="StartDate" name="StartDate" type="date" value="">

I made an some code in this manner

$(document).ready(function () {
    debugger;
    var date = $('#StartDate').val();
    var dt = new Date(date);
    var day = parseInt(dt.getDate());
    var month = parseInt(dt.getMonth() + 1);
    var year = parseInt(dt.getFullYear());

    if (day < 10) { day = '0' + day }
    if (month < 10) { month = '0' + month }
    var setDate = year + '-' + month + '-' + day;

    $('#StartDate').val(setDate);
});

When the program runs I see the value from the debugger screen is string.empty

var date = "";

also I tried to remove this one the lower portion of format error again.

var dt = new Date(date);

but I didnt work. if anyone knows the answer to this I really need help Finally Coming data in view but value does not show because of format is different. This required format(yyyy-MM-dd)

Thank you to everyone.

Upvotes: 0

Views: 838

Answers (1)

user3559349
user3559349

Reputation:

Your script is unnecessary, and since property StartDate is a nullable DateTime? and has no value (your html has value="") then var dt = new Date(date); will return Invalid date because var date = $('#StartDate').val(); returns null and the script fails.

You need to set the value of StartDate in the controller before you pass the model to the view, for example

var model = new MyModel() { StartDate = DateTime.Today };
return View(model);

which will display today's date in the input.

In order to display the required format, you can add the DisplayFormatAttribute

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime? StartDate { get; set; }

Note adding the DataTypeAttribute means you can omit the type="date" from your EditorFor() method as that will be added by the method

Alternatively you can omit both attributes and use

@Html.TextBoxFor(m => m.StartDate, "{0:yyyy-MM-dd}", new { @class = "form-control", type = "date" }})

Upvotes: 1

Related Questions