MVC4 Date Picker with Default Date

2020-06-15 17:42发布

问题:

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?

回答1:

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; }
}



回答2:

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; }
}


回答3:

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);
    });