0

I'm trying to use the jQuery datepicker within my MVC application, but every time I submit the form, something goes wrong; may it be a wrong conversion of the date, or simply null.

It's difficult to explain, so I'd rather show in code.

Controller function

[HttpPost]
public ActionResult GetData(ReportViewModel model)
{
    using (var eh = new ExcelHelper())
    {
        var data = new List<ReportDataModel>(); 
        if (!model.SpecificTimeline) { //Do something! }
        else if (model.SpecificTimeline) { //Do something else! }

        return View("Index", model);
    }
}

Controller index

public ActionResult Index(ReportViewModel model = null)
{
    using (var eh = new ExcelHelper())
    {
        if (model.Data == null)
        {
            model = new ReportViewModel(false, DateTime.Now.AddMonths(-1), DateTime.Now, eh.GetRawReportData());
        }
        return View(model);
    }
}

Markup (HTML)

<div>
    @using (Html.BeginForm("GetData", "Report", FormMethod.Post))
    {
    <div class="form-horizontal">

        <div class="form-group">
            @Html.LabelFor(model => model.SpecificTimeline, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.CheckBoxFor(model => model.SpecificTimeline, new { @class = "" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.StartDate, new { @class = "control-label col-md-2 " })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.StartDate, new { @class = "form-control datepicker" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.EndDate, new { @class = "control-label col-md-2 " })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.EndDate, new { @class = "form-control datepicker" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Generate Report" class="btn btn-primary" />
            </div>
        </div>
    </div>
    }
</div>

JS (Only used to convert the Datetime to the correct format)

@using (Html.BeginScripts())
{

    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/themes/base/jqueryui-datepicker")

    <script>
        $(function () {
            var startDate = new Date('@Model.StartDate');
            var endDate = new Date('@Model.EndDate');

            $('.start-date').datepicker({
                dateFormat: 'mm-dd-yy'
            }).datepicker('setDate', startDate);

            $('.end-date').datepicker({
                dateFormat: 'mm-dd-yy'
            }).datepicker('setDate', endDate);
        });
    </script>
}

Quick look at the model

public class ReportViewModel
{
    public ReportViewModel() { }

    public ReportViewModel(bool specificTimeline, DateTime startDate, DateTime endDate, List<ReportDataModel> data)
    {
        SpecificTimeline = specificTimeline;
        StartDate = startDate;
        EndDate = endDate;
        Data = data;
    }

    public bool SpecificTimeline { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime StartDate { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime EndDate { get; set; }

    public List<ReportDataModel> Data { get; set; }
}

Problem

Whenever I select to dates;

startDate: 17-02-2016
endDate: 22-02-2016

format: dd-mm-yy

and I press the submit button "Generate Report", I want the function GetData(ReportViewModel model) to be hit, and generate the parameter model with the correct data. This is not happening as the EndDate property is 01-01-0001, even though I selected a date from the datepicker.

Edit

I have noticed that the DateTime properties are equal to 01-01-0001 if I don't select anything in the datepicker input. If I do select a new date in both fields, the date in correct in the model that generates when the function Getdata() is hit!

So if I do not touch the inputs, the date gets set to the default 01-01-0001.

Any workaround to that?

tereško
  • 58,060
  • 25
  • 98
  • 150
Detilium
  • 2,868
  • 9
  • 30
  • 65

1 Answers1

2

Since you are only passing only date try specifying the type of model property as [DataType(DataType.Date)] instead of [DataType(DataType.DateTime)].

Read some more information here.

Also not necessarily, but please refer answers in this post on using EditorFor instead of TextBoxFor

halfer
  • 19,824
  • 17
  • 99
  • 186
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
  • I don't know which one did the trick, but I changed the type to be `[DataType(DataType.Date)]` instead of the old, and also tried following the link you provided. Something did the trick as it seems to be working now. I only have one question though; How do I make the date format correctly the first time the view gets created? – Detilium Feb 22 '16 at 10:43
  • You can specify it in the `razor` template itself something like `@model.Date.ToString("dd MMM yyyy")` by converting to `string` while displaying the `view` or adding `[DisplayFormat]` annotation to your model property as `[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")] public DateTime Date { get; set }` - **[Source](http://stackoverflow.com/questions/4679352/converting-datetime-format-using-razor)** – Guruprasad J Rao Feb 22 '16 at 10:47
  • None of these seem to help. If I try `@model.Date.ToString("dd/mm/yyyy")` within the input tag, I get an error. Using the `[DisplayFormat(DataFormatString("dd/mm/yyyy"))]` does nothing. – Detilium Feb 22 '16 at 12:21
  • That is just for `displaying` not in view not in `Editor` – Guruprasad J Rao Feb 22 '16 at 12:58