View passing date to Model in wrong format

2

I am using Bootstrap-Datapicker as the date field on 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 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 once it is sent to the model:

Settingthepropertyinmymodel:

[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 Razor to generate my form, but I'm still learning and I feel more comfortable with Html , for now.

    
asked by anonymous 14.11.2015 / 21:41

1 answer

1

Oops, assuming you have more models with a date, it pays to create a customizable ModelBinder for your DateTime that will be bound 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
    }

Then you register your new DateTimeModelBinder in your Global.asx

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

It looks like you will not need the globalization setting in your web.config.

This Scott article can help you. link

    
16.11.2015 / 22:05