Anup
Anup

Reputation: 9746

MVC - Date Format Conversion getting Date as null

I am using Jquery ui datepicker, the dateFormat is set to dd/mm/yyyy. My Local machine Server date format is set to mm/dd/yyyy. So i converted the format in View.

<input type="text" class="form-control datepicker" value="@string.Format("{0:dd/MM/yyyy}", DateTime.Now)" name="LoanDate" required  />

In my model on POST, I get LoanDate as null.

If I reset My Local machine date format to dd/mm/yyyy, I get the LoanDate in my Controller POST method.

How to solve this Issue?

Upvotes: 0

Views: 1953

Answers (1)

Anup
Anup

Reputation: 9746

This is how i solved it :-

public class UTCDateTimeModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            // Check if the DateTime property being parsed is not null or "" (for JSONO
            if (value.AttemptedValue != null && value.AttemptedValue != "")
            {
                // Parse the datetime
                var dt = DateTime.ParseExact(value.AttemptedValue, "dd/MM/yyyy", CultureInfo.InvariantCulture);                
                return dt;
            }
            else
            {
                return null;
            }
        }
    }

In Global.asax - Application_Start() :-

var binder = new UTCDateTimeModelBinder();
ModelBinders.Binders.Add(typeof(DateTime), binder);
ModelBinders.Binders.Add(typeof(DateTime?), binder);

Now i get LoanDate Value in my Model in dd/MM/yyyy format.

http://www.martin-brennan.com/custom-utc-datetime-model-binding-mvc/

Upvotes: 1

Related Questions