Problem with Dates in ASP.NET MVC

2

In my model I have the following field:

[Column("sdt_DataReferencia")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[Display(Name = "Data Referência")]
[DataType(DataType.Date)]
public DateTime DataReferencia { get; set; }

I often pass it through actions :

@Url.Action("Create", "Cobranca", new { reference = Model[i].DataRef.Value.ToString("01/MM/yyyy"), IDC = Model[i].Cliente.ClienteId }) "

But it has reversed month by day!

What is the best way to work with date? always use default yyyy-MM-dd and only for display do the conversion?

    
asked by anonymous 07.03.2016 / 18:55

1 answer

1

This is solved by implementing a DateTimeModelBinder :

public class DateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        object result = null;

        string modelName = bindingContext.ModelName;
        string attemptedValue = bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;

        if (String.IsNullOrEmpty(attemptedValue))
        {
            return result;
        }

        try
        {
            result = DateTime.Parse(attemptedValue);
        }
        catch (FormatException e)
        {
            bindingContext.ModelState.AddModelError(modelName, e);
        }

        return result;
    }
}

Register it for types DateTime and DateTime? on Global.asax.cs :

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());
    ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());

    ...
}

Also configure globalization on your Web.config :

<system.web>
  ...
  <globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" />
  ...
</system.web>
    
12.07.2016 / 21:31