Assume that a model has a datetime datatype. So in view there will be a blank field ask you to input datetime.
Is there a way to fill this HTML field with today's date/datetime as default value?
Assume that a model has a datetime datatype. So in view there will be a blank field ask you to input datetime.
Is there a way to fill this HTML field with today's date/datetime as default value?
model.SomeDateField = DateTime.Now(); return View(model); Simple
<%: Html.TextBox("date", DateTime.Now.ToShortDateString()) %> Or use javascript to get the client's browser date. Better yet use jquery's datepicker for nice UI for selecting dates. With it you can also prepopulate the default date:
/** Enable jquery UI datepickers **/ $(document).ready(function () { $(function () { $(".date-select").datepicker({ dateFormat: 'dd.mm.yy' }); $(".date-select").datepicker($.datepicker.regional['sl']); }); $(function () { $("#someDateField").datepicker('setDate', new Date()); }); }); Wanted to add what I found that I needed for filling a datepicker with today's date that was being generated from the DateTime data type in HTML5 (via razor at the view in the value attribute) which is this:
@Html.TextBoxFor(model => model.YourDateInModel, new { @id = "YourDateId", @type = "date", @Value = DateTime.Now.ToString("yyyy'-'MM'-'dd") }) Note that the ToString() format was necessary to get it to show the date in the datepicker field (it requires a database format).
Source: https://forums.asp.net/p/2154640/6320474.aspx?p=True&t=637376668781782563
Edit: This ended up leaving the database blank/null by itself, so I also had to set the model with the initial value of today's date (as mentioned above).
public DateTime YourDateInModel { get; set; } = DateTime.Now; In my case I needed both. It may also be helpful to use something like:
$("#YourDateId").prop("disabled", true); If you are using JQuery/Javascript to prevent changes to the field where applicable.
You can use simple javascript for that.
Put this code in the header:
<script> function setToCurrentDate(inputElement) { var currentDate = new Date().toISOString().split('T')[0]; inputElement.value = currentDate; } </script> Add a body tag to the document and set its onload like this:
<body onload="setToCurrentDate(document.getElementById('dataInput'));"> *Do not forget to close the body tag at your page in the proper place.
And at last, set the onfocus of your date control with: "setToCurrentDate(this)"
<input class="form-control" id="dataInput" type="date" data-val="true" data-val-required="this field is mandatory." name="Data" onfocus="setToCurrentDate(this)" /> <input name="__Invariant" type="hidden" value="Data" /> It worked very fine for me.