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?

4
  • you have 2 options, use mm/dd/yyyy formatg in your server, or before post the data convert that date to mm/dd/yyyy Commented Feb 16, 2015 at 6:06
  • how are you posting the data without a name of the field? I would use javascript to convert on the fly. Commented Feb 16, 2015 at 6:06
  • Please check the answer out with 49 (or more) votes: stackoverflow.com/questions/2356601/… Commented Feb 16, 2015 at 7:12
  • value=" @DateTime.Now.ToString("dd/MM/yyyy")" Commented Feb 16, 2015 at 7:31

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.