11 October 2015

DateTime model property is not assigned value in Model binding

Recently one junior member in the team was building a web page using ASP.NET MVC; he was using model binding to get the model properties posted back.

// ViewModel definition
public class InsurancePolicy
    public DateTime MaturityDate;
// Controller sample
public ActionResult Edit(InsurancePolicy policy)
   // policy.MaturityDate was not assigned correct 
   // value posted back
    DateTime policyMaturityDate= policy.MaturityDate;
    //Other logic..
    return RedirectToAction("PurchasedPolicyList");

But however whenever the Edit form is posted back the policy. The Maturity Date was having the default value for the date time, but not the posted back value.

Later after looking into the code, found out below:

  1. He was selecting the policy date time field, in the DD/MM/YYYY format.
  2. But the server had “MM/DD/YYYY” date format set.

Requirement was not to change the UI date time selection format and also changing the server date time format was not a feasible solution, given that application may be hosted in cloud environment, where you may don't have permission to do such changes to the system.

Later System.Globalization.CultureInfo class came to rescue. Added the below in the web.config file to let know application should with INDIA(hi-IN) culture info.

 <globalization culture="hi-IN" uiCulture="en-US" />

After having the above globalization setting, the Maturity Date time properties started getting the right values.

Caution: Before changing the setting at the global level, care must be taken to ensure it doesn't have any adverse effect on the web application.

No comments:

Post a Comment