I have a Textbox
with type as date
. I am trying to set default value of the textbox
to current date.
@Html.TextBoxFor(x => x.Date, new { @id = "Date", @type = "date",
@value = DateTime.Now.ToShortDateString() })
The above line doesn't set default value. How to set default value as current date?
As Stephen Muecke said, you need to set the property's value on the model.
// in controller method that returns the view.
MyModel model = new MyModel();
model.Date = DateTime.Today;
return View(model);
And your Razor would be:
@Html.TextBoxFor(x => x.Date, "{0:yyyy-MM-dd}", new { @class = "form-control", @type = "date"})
Note that the id
and the name
properties should be automatically assigned to the property name when using a For
method, such as @Html.TextBoxFor()
, so you don't need to explicitly set the id
attribute.
It's better way to manage in view
@Html.TextBoxFor(x=> x.Date, new { @Value = @DateTime.Now.ToShortDateString() })
<input asp-for="date" value="@DateTime.Today" type="datetime" class="form-control" />
This works for me. Remember to change 'date' according to your model.
and use this, if you need time as well
<input asp-for="date" value="@DateTime.Now" type="datetime" class="form-control" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With