Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 Date Picker with Default Date

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:

Empty Date Picker

QUESTION:

How can I get today's date (from controller) to display here instead?

like image 442
JSK NS Avatar asked Jan 27 '14 23:01

JSK NS


3 Answers

You should do this from jQuery level:

   $( ".selector" ).datepicker( "setDate", yourDate);

For example, if you want to set the today's date:

   $( ".selector" ).datepicker( "setDate", new 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:

public class EmployeeIndexViewModel
{
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime ToDate { get; set; }
}
like image 51
Paweł Bejger Avatar answered Nov 08 '22 18:11

Paweł Bejger


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:

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

Correctly displaying date time

like image 28
JSK NS Avatar answered Nov 08 '22 17:11

JSK NS


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

   $(document).ready(function () {
        var dateNewFormat, onlyDate, today = new Date();

        dateNewFormat = today.getFullYear() + '-';
        if (today.getMonth().length == 2) {

            dateNewFormat += (today.getMonth() + 1);
        }
        else {
            dateNewFormat += '0' + (today.getMonth() + 1);
        }

        onlyDate = today.getDate();
        if (onlyDate.toString().length == 2) {

            dateNewFormat += "-" + onlyDate;
        }
        else {
            dateNewFormat += '-0' + onlyDate;
        }

        $('#mydate').val(dateNewFormat);
    });
like image 34
Radha Anil K Avatar answered Nov 08 '22 19:11

Radha Anil K