View passing date to Model in wrong format

Asked

Viewed 895 times

2

I’m using Bootstrap-Datapicker as date field in my form and globalizing with moment-with-locales.

The configuration I used is as follows::

$('.datetimepicker').datetimepicker({
    locale: 'pt-br',
    format: 'L'
});

The format L is DD/MM/YYYY within the moment-with-locales.js:

longDateFormat : {
    LT : 'HH:mm',
    LTS : 'LT:ss',
    L : 'DD/MM/YYYY',
    LL : 'D [de] MMMM [de] YYYY',
    LLL : 'D [de] MMMM [de] YYYY [às] LT',
    LLLL : 'dddd, D [de] MMMM [de] YYYY [às] LT'
},

But when I choose a date it is passed to the format MM/dd/yyyy as soon as it is sent to the model:

Escolhendo a data 02/11/2015

Debugando o model

Formato que volta para a View

Setting the property in my model:

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? DataInicio { get; set; }

And I’m using globalization setting in my web.config:

<system.web>
  <globalization uiCulture="pt-BR" culture="pt-BR" />
  <compilation debug="true" targetFramework="4.5.2" />
  <httpRuntime targetFramework="4.5.2" />
</system.web>

And finally my field in View:

<div class="input-group date datetimepicker" id="datetimepicker1">
    <input type="text" class="form-control" name="DataInicio" placeholder="Data Inicial" value="@Model.DataInicio" />
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
    </span>
</div>

And just as an observation, I know I could use the Razor to generate my form, but I’m still learning and feel more at ease with Html, for the time being.

  • Try to pull out [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] or switch to [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")] `

  • I had already tried both possibilities before posting @Randrade. I forgot to say this in the question, sorry.

1 answer

1

Opa, assuming that you will have more models with date, it is worth you create a customizable Modelbinder for your Datetime that maybe will be linked from View to Model.

public class DateTimeModelBinder : IModelBinder
    {
        #region Fields


        private readonly string _customFormat;

        #endregion

        #region Constructors and Destructors

       public DateTimeModelBinder(string customFormat)
        {
            this._customFormat = customFormat;
        }

        #endregion

        #region Explicit Interface Methods

        object IModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            return DateTime.ParseExact(value.AttemptedValue, this._customFormat, CultureInfo.InvariantCulture);
        }

        #endregion
    }

Next you register your new Datetimemodelbinder in your Global.asx

ModelBinders.Binders[typeof(DateTime)] = 
           new DateAndTimeModelBinder() { CustomFormat = "yyyy-mm-dd" };

It seems to me that you will not need to configure globalization on your web.config.

This Scott article might help you. http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.