1

I'm using JQueryUI Datepicker in my ASP.NET MVC 5 project. I want user to enter dates in mm/dd/yy format in Create and Edit views. This is what I accomplished so far :

This is my model :

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

This is jQuery code in _Layout.cshtml :

<script type="text/javascript">
    $(function () {
        $('.date-picker').datepicker({ dateFormat: "MM-dd-yy" });
    })
</script>

In create View I have this : enter image description here

In Edit View I have this : enter image description here

If I don't touch Date in Edit and hit Save, I get a warning saying :

The field ProjectDeadline must be a date.

I tried many possibilities to have what I want, but that's the best I can get. I got errors in my most of attempts. Can you tell me how I can fix my code to get mm/dd/yyyy format in Date fields properly? Thanks.

jason
  • 6,962
  • 36
  • 117
  • 198
  • Your error is associated with `jquery.validate.js`. If your not using the `mm/dd/yyyy` format, then you need to modify the validator. Refer [this answer](http://stackoverflow.com/questions/27285458/jquery-ui-datepicker-and-mvc-view-model-type-datetime/27286969#27286969) for an example –  Dec 04 '15 at 08:58

2 Answers2

5

I've had this issue multiple times, but I have come up with the CustomDateTimeModelBinder which looks at the DisplayFormat attribute and binds it to the model:

// <summary>
/// This makes the model binder able to find a custom datetime format
/// </summary>
public class CustomDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!String.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", String.Empty).Replace("}", String.Empty);
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("{0} is an invalid date format", value.AttemptedValue));
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

In your application startup, wire it up:

ModelBinders.Binders.Add(typeof(DateTime?), new CustomDateTimeModelBinder());

janhartmann
  • 14,713
  • 15
  • 82
  • 138
  • You mean, I should wire it up in Startup.Auth.cs ? – jason Dec 04 '15 at 09:29
  • Yes or Global.asax, Startup.cs or what you use :-) – janhartmann Dec 04 '15 at 09:30
  • Thank you, I did what you said. I'm still getting an error. It still says it's not a valid Date. I changed in jQuery and model to `mm-dd-yyyy` – jason Dec 04 '15 at 09:43
  • Where have you inserted the code, what value is the input (in the debugger)? – janhartmann Dec 04 '15 at 09:44
  • Maybe try adding the line without the nullable: `ModelBinders.Binders.Add(typeof(DateTime), new CustomDateTimeModelBinder());` – janhartmann Dec 04 '15 at 10:02
  • Thanks, it worked! But there is one problem : After I create an object, I go to Edit View, the date looks like the image in the question. And if don't touch Date and click Save. I get : `The field ProjectDeadline must be a date.`. Thank you. – jason Dec 04 '15 at 11:01
  • 1
    You have to format the date to the format you need in the view. – janhartmann Dec 04 '15 at 11:35
0

try data-date-format = 'mm-dd-yyyy' in div datepicker :

div class="input-group date date-picker" data-date-format="yyyy-mm-dd">
     @Html.EditorFor(model => model.ProjectDeadline, new {     htmlAttributes     = new { @class = "form-control", @maxlength = "10"} })
...
/div>