Search code examples
asp.net-mvcjquery-uidatetimedatepickerajax.beginform

MVC ajax form submission returns default date of DateTime property


I am using the below Ajax form to select and post date ranges.

View Model:

public class ViewFormSubmissionsVM
    {
        public string FormName { get; set; }
        public Guid FormId { get; set; }

        [Display(Name="From:")]
        public DateTime From { get; set; }

        [Display(Name = "To:")]
        public DateTime To { get; set; }
    }

Razor/HTML:

@model ViewFormSubmissionsVM

    @using (Ajax.BeginForm("ViewFormSubmissions", "Form", new AjaxOptions { HttpMethod = "POST", OnSuccess = "onGetSubmissionSuccess", OnFailure = "onGetSubmissionError" }, new { @class = "form-horizontal" }))
    {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(x => x.FormId)
        <div class="row col-md-12">
            <div class="pull-right">
                <label class="control-label col-md-3">@Html.DisplayNameFor(x => x.From)</label>
                @Html.TextBoxFor(x => x.From, "{0:MM/dd/yyyy}", new { @class = "form-control col-md-3", @data_picker = "date-picker" })
                <label class="col-md-3">@Html.DisplayNameFor(x => x.To)</label>
                @Html.TextBoxFor(x => x.To, "{0:MM/dd/yyyy}", new { @class = "form-control col-md-3", @data_picker = "date-picker" })
                <input type="submit" class="btn btn-primary" value="Search" />
            </div>
        </div>
    }

JQuery Date picker:

$(document).ready(function () {
    $('*[data-picker="date-picker"]').datepicker();
});

This issue is while submitting the form, the "From" and "To" Datetime properties, received the default date values instead of selected.

enter image description here

Am I missing anything important!! I have already used these codes in different forms, but never experienced this before.

Could any one help me to get out of this one.

Many Thanks.


Solution

  • First of all, I think you should call this overload:

    using (Ajax.BeginForm("ViewFormSubmissions", "Form", null, new AjaxOptions{ 
        HttpMethod = "POST", 
        OnSuccess = "onGetSubmissionSuccess", 
        OnFailure = "onGetSubmissionError" 
        }, 
        new {@class = "form-horizontal" }))
    

    with null as 3rd parameter.

    Second, check your datetime format. You can find more info here: MVC DateTime binding with incorrect date format, ASP.NET MVC datetime culture issue when passing value back to controller or http://weblogs.asp.net/melvynharbour/mvc-modelbinder-and-localization.