jason
jason

Reputation: 7164

Stuck with Date format in ASP.NET MVC 5

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.

Upvotes: 1

Views: 1003

Answers (2)

janhartmann
janhartmann

Reputation: 15003

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

Upvotes: 5

gaauspawcscwcj
gaauspawcscwcj

Reputation: 3

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>

Upvotes: 0

Related Questions