0

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Anup
  • 9,396
  • 16
  • 74
  • 138
  • you have 2 options, use mm/dd/yyyy formatg in your server, or before post the data convert that date to mm/dd/yyyy – bto.rdz Feb 16 '15 at 06:06
  • how are you posting the data without a name of the field? I would use javascript to convert on the fly. – Judson Terrell Feb 16 '15 at 06:06
  • Please check the answer out with 49 (or more) votes: http://stackoverflow.com/questions/2356601/custom-datetime-model-binder-in-asp-net-mvc – Ako Feb 16 '15 at 07:12
  • `value=" @DateTime.Now.ToString("dd/MM/yyyy")"` – Manoz Feb 16 '15 at 07:31

1 Answers1

1

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/

Anup
  • 9,396
  • 16
  • 74
  • 138