MVC Razor - Default Value as Current date for textbox type date
<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" />
It's better way to manage in view
@Html.TextBoxFor(x=> x.Date, new { @Value = @DateTime.Now.ToShortDateString() })
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.