Date Issue in ASP.NET MVC

Asked

Viewed 1,049 times

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 usually pass her by actions:

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

But she has reversed month by day!

What is the best way to work with date? always use the default yyyy-MM-dd and just to show off I do the conversion?

  • The best way, for me, is the format in which I don’t need to convert any time. Try to work in a pattern in which you will have the least effort possible.

  • but I cannot pass through querystring the Brazil dd/mm/yyyy pattern and I have problems displaying values in this format, so I changed to yyyy-MM-dd

  • It would not be better if you set the culture on the web.config and so already deal with dates in Brazilian format?

  • I already did and still in the querystring he changes

1 answer

2


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 the guys DateTime and DateTime? in the 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 in your Web.config:

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

Browser other questions tagged

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