ASP.NET MVC Post Date Format

2

I have a form that sends via post the search parameters, however the parameter of type date whenever it arrives in the action the month and day are inverted, for example, if I put in the page the date 04/03/2016 in the control arrives 03/04/2016

@model CaixaIndexViewModel

<div class="panel panel-default">
    <div class="panel-heading">
        Pesquisa de caixas
    </div>
    <div class="panel-body">
        @using (Ajax.BeginForm(actionName: "Pesquisa", controllerName: "Caixa",
                                            routeValues: new { page = 1 },
                                            ajaxOptions: new AjaxOptions
                                            {
                                                HttpMethod = "GET",
                                                InsertionMode = InsertionMode.Replace,
                                                UpdateTargetId = "unobtrusive",
                                                OnComplete = "onComplete"
                                            }))
        {
            <div class="row">
                <div class="col-lg-12">
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label>Nome</label>
                            <input type="text" class="form-control" id="nome" name="nome" value="@ViewBag.nome" />
                        </div>

                        <div class="col-lg-3">
                            <label>Data</label>
                            <input type="date" class="form-control" id="data" name="data" value="@ViewBag.data" />
                        </div>

                        <div class="col-lg-3">
                            <label>Valor R$</label>
                            <input type="text" class="form-control" id="valor" name="valor" value="@ViewBag.valor" />
                        </div>
                    </div>
                    <div class="btn-group">
                        <button type="submit" class="btn btn-primary" id="btnPesquisar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>
                </div>
            </div>
        }

        <div class="row">
            <div class="col-lg-12">
                <div class="btn-group" role="group">
                    @if (Model.CaixaControle == null || Model.CaixaControle.DataHoraFechamento.HasValue)
                    {
                        <a class="btn btn-default" href="@Url.Action("AbrirCaixa")"><i class="fa fa-folder-open fa-fw"></i> Abrir caixa</a>
                    }
                    else
                    {
                        if (Model.CaixaControle.DataHoraAbertura.Date == DateTime.Now.Date)
                        {
                            <a class="btn btn-default" href="@Url.Action("Create")"><i class="fa fa-plus fa-fw"></i> Novo</a>
                        }
                        <a class="btn btn-default" href="@Url.Action("FecharCaixa")"><i class="fa fa-close fa-fw"></i> Fechar caixa</a>
                    }

                    @if (Model.Pesquisa.Count() > 0)
                    {
                        <a class="btn btn-default" id="editar" href="#"><i class="fa fa-pencil fa-fw"></i> Editar</a>
                        <a class="btn btn-default" id="detalhes" href="#"><i class="fa fa-file-text-o fa-fw"></i> Detalhes</a>
                        <a class="btn btn-default" id="excluir" href="#"><i class="fa fa-trash-o fa-fw"></i> Excluir</a>
                    }
                </div>

                <div id="unobtrusive">
                    @Html.Partial("_Pesquisa", Model)
                </div>
                <div id="oncomplete"></div>
            </div>
        </div>
    </div> <!--End ./panel-body-->
</div>

@section Scripts{
    <script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
@Scripts.Render("~/bundles/jqueryval")

    <script>
        function formataLinks() {

            $(document).ready(function () {

                function SetLinks(valor) {
                    if (valor != null) {
                        $("#editar").attr("href", "@Url.Action("Edit")?Id=" + valor);
                        $("#detalhes").attr("href", "@Url.Action("Details")?Id=" + valor);
                        $("#excluir").attr("href", "@Url.Action("Delete")?Id=" + valor);
                    }
                    else {
                        $("#editar").attr("href", "#");
                        $("#detalhes").attr("href", "#");
                        $("#excluir").attr("href", "#");
                    }
                }

                var item = Cookies.get('rdCaixaId');
                $("input[name='rdCaixaId']").prop("checked", false);
                $("input[name='rdCaixaId'][value='" + item + "']").prop("checked", true);

                SetLinks(item);

                $("input[name=rdCaixaId]").click(function () {
                    SetLinks($(this).val());

                    Cookies.set('rdCaixaId', $(this).val());
                });
            });
        }

        function onComplete() {
            formataLinks();
        }

        function PagedOnComplete(obj) {
            console.log(obj);
            var $oncomplete = $('#oncomplete');
            $oncomplete
                .text('Paging operation completed.')
                .css('backgroundColor', 'yellow')
                .fadeOut({
                    complete: function () {
                        $oncomplete.css('backgroundColor', 'transparent').text('').show();
                        formataLinks();
                    }
                });
        }

        formataLinks();
    </script>
}

Controller

public ActionResult Index()
        {
            var nome = Request.Cookies["caixa.nome"]?.Value ?? "";

            var descricao = Request.Cookies["caixa.descricao"]?.Value ?? "";

            DateTime data = DateTime.Now.AddMonths(-1);
            DateTime.TryParse(Request.Cookies["caixa.data"]?.Value ?? "a", out data);
            if (data == DateTime.MinValue)
                data = DateTime.Now.AddMonths(-1);

            decimal valor = 0;
            decimal? valorPesquisa = null;
            if (decimal.TryParse(Request.Cookies["caixa.valor"]?.Value ?? "a", out valor))
            {
                valorPesquisa = valor;
            }

            int page = 1;
            int.TryParse(Request.Cookies["caixa.page"]?.Value ?? "1", out page);

            return Pesquisa(page, nome, data, valorPesquisa);
        }

        public ActionResult Pesquisa(int page, string nome, DateTime data, decimal? valorPesquisa = null)
        {
            data = data.Date;

            Response.Cookies["caixa.page"].Value = page.ToString();

            Response.Cookies["caixa.nome"].Value = nome;
            ViewBag.nome = nome;

            Response.Cookies["caixa.data"].Value = data.ToString();
            ViewBag.data = data;

            Response.Cookies["caixa.valor"].Value = valorPesquisa.ToString();
            ViewBag.valor = valorPesquisa;

            var caixas = from c in context.Caixa
                         where c.DataHoraCad >= data
                         orderby c.DataHoraCad descending
                         select new CaixaPesquisaModel()
                         {
                             CaixaId = c.CaixaId,
                             Descricao = c.Descricao,
                             Nome = c.Pessoa.Nome,
                             DataHora = c.DataHoraCad,
                             Observacao = c.Observacao,
                             Tipo = c.Tipo,
                             Valor = c.Valor
                         };

            int pageSize = 10;
            var itens = caixas.ToPagedList(page, pageSize);

            var caixaControle = context.CaixaControle
                .Where(a => a.UsuarioCaixa == this.Usuario)
                .OrderByDescending(a => a.DataHoraAbertura)
                .FirstOrDefault();

            var model = new CaixaIndexViewModel()
            {
                CaixaControle = caixaControle,
                Pesquisa = itens,
            };

            if (Request.IsAjaxRequest())
                return View("_Pesquisa", model);

            return View(model);
        }
    
asked by anonymous 10.03.2016 / 16:04

1 answer

1

I have the same problems with my systems. I've implemented a DateTimeBinder that solves the problem:

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;
    }
}

You need to register this Model Binder at the beginning of the application (Global.asax):

    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());

        ...
    }

Also check if your Web.config contains the following:

<system.web>
  <authentication mode="None" />
  <compilation debug="true" targetFramework="4.5.2" />
  <customErrors mode="Off" />
  <httpRuntime targetFramework="4.5" />
  <globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" />
</system.web>
    
10.03.2016 / 16:39