Skip to main content

DateTime format and decimal or currency issue resoved using Custom model binders in MVC

Hi all,

You can't keep yourself away from writing blog when you have faced an issue while development and you tried to solve it and finally you come across something interesting which finally resolved the issue

Today's post is regarding the scenario which we face in day to day life (But i faced it for the first time today) where i had multilingual application running on telerik controls

One of the page had DateTimePicker,We have "da-DK" (Danish) clients,When tried to save Date from one page,The page kept on giving error message "DateTime format is not valid" for this field (Typical MVC datetime validation error messgae)

So scenario was in UI everything was coming as per culture,If i select date from DatePicker it was returning correct format,But still couldn't figure out what was wrong

So let me cut the story short and tell you,Model binder was the key to success

The code looks like following

public class DateTimeModelBinder : IModelBinder
{
  public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
  {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            ModelState modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            try
            {
                string culture = Convert.ToString(HttpContext.Current.Session["culture"]);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
                actualValue = Convert.ToDateTime(valueResult.AttemptedValue, Thread.CurrentThread.CurrentCulture);
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
  }
}

Above is simple class created under folder "Helper",Now what it does is it tells compiler that which format the date should be parsed so that its valid on server

Now,We are not done yet,We need to register this binders in global.asax file on Application_Start so that at runtime this class gets called and later on can parse the date as per culture,Which is like below

protected void Application_Start()
{
     AreaRegistration.RegisterAllAreas();
     RegisterGlobalFilters(GlobalFilters.Filters);
     RegisterRoutes(RouteTable.Routes);
           
      ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
     WebAssetDefaultSettings.UseTelerikContentDeliveryNetwork = true;
}


Now,Try to submit the date which previously you were trying to in different culture and all will work,Same applies for currency,You can use Convert.Deciaml() instead of Convert.DateTime

Cheers!!!

Comments

  1. Dear Daivagna,

    As far as DateTime issue is concerned can be also resolved by a usage of property which has been instantiated within CultureInfo class. Though above one is quite useful too.

    Good One bro :)

    Regards,
    ...Sapan

    ReplyDelete
  2. Thanks

    Can you provide small sample? As app is already dealing with culture and in mvc when you use helper classes those properties automatically coverts itself to datetime picker and that also culture wise

    ReplyDelete

Post a Comment

Popular posts from this blog

Why SitecoreAI - Getting into the shoes of the customer how to select right CMS

Hi Team, Lately, I have been talking to lot of our customers / potential customers and having pre-sales demos where one question always comes is "Why Sitecore" ?  Now this question can be for any product which is out for sell. And as a technician I always get into product technical features, but at the same time as a pre-sales guy, it also makes me think, surely all competitive products have same features, so definitely answer to this is not in the technicalities.  If you step back and think, we are also a customer in our daily life and buy lot of things, what is that process we go through? When we buy, how can your customer decide if this is a right fit for you or not, why we select A over B? Is it price? is it service? Is it a brand? Is it about features? Is it about brand loyalty?  When it is a technical product, I am sure it cannot start with the technicalities of the product or selecting product itself, 100% not, I feel decision is always business strategy first and ...

Hell of sitecore aliases pipeline breaking the site with 500 error

Hello Friends, I belive this blog post is very important for everyone because, It has some very serious effect on working of your headless website, i will share my experience what we faced and how we resolved it Issue we started facing Our site started giving "Key cannot be null or empty" with YSOD like following  Side affect Because of this 500 error, Our site pages were showing 500 custom error page intermittently and our MAU (Monthly Active User) drop rate increased. Sitecore KB There is already Sitecore KB article talking about this error but the patch which is provided on this link is confusing as well as very huge and it could bring other issues along with it as that upgrade patch also has lot of other things too which i did not want to introduce in our stable CMS. Known Issues - Retrieving the child items of resource items is not thread-safe Observation Though the surfaced exception was looking similar and giving same error and behavior given on this article, We looked...

401.1 Unauthorized with windows authentication error code 0xc000006d

How many of you have faced this hosting issue when you do everything what it takes to run the site with windows authentication but still you are getting the same error again and again? If you think you also have faced the same issue and you tired of reading MSDN KBs for it and still have not found the issue (If KB has solved the issue, well and good, if not you can try this trick),Please Read below Typical scenario In typical hosting with IIS, i did every possible things like enabling windows authentication, changing it in web.config, configuring connection pool, authorization rules, it asks me for window authentication login and despite of entering correct credentials it always fails and keeps on asking for login, and when pressed cancel it gives 401.1 with 0xc000006d error code Solution (Which worked for me at-least after trying for almost 6-9 hrs) You need to change the Loop Back Check in registry so that it allows the host names which you are giving in url are allowed and au...