I am using MVC4 with the Razor view engine. My controller is as follows:
public ActionResult Index()
{
return View(new EmployeeIndexViewModel
{
ToDate = DateTime.Now
});
}
My View Model is as follows:
public class EmployeeIndexViewModel
{
[DataType(DataType.Date)]
public DateTime ToDate { get; set; }
}
On my view I have a simple EditorFor()
call:
@Html.EditorFor(model => model.ToDate)
But still get a default (masked) value in my date picker:
QUESTION:
How can I get today's date (from controller) to display here instead?
U can set the Input or Input with type="date" (datetimepicker) using JQuery.
In Razor view
@Html.TextBoxFor(m => m.StartedDate, new { @id = "mydate", @type = "date", @class = "form-control" })
Here is the JS code
My problem was not a jQuery or MVC4 problem as I had initially thought. It has to do with how the HTML5 compatible browser displays the date picker. I was passing the date to the view in the incorrect format.
I modified my ViewModel to this and now the date populates correctly:
You should do this from jQuery level:
For example, if you want to set the today's date:
You can also try adding the
DisplayFormat
attribute in your view model class to make sure that the date picker will interpret your data format correctly: