Search code examples
c#asp.netasp.net-mvcdatetimeredirecttoaction

ASP.NET RedirectToAction change DateTime format in request


I'm working in an app based on ASP.NET MVC and I have this issue, when I make a RedirectToAction in a method, it change my DateTime format in the Request property of the ControllerBase Class.

For Example:

public class MyController:Controller{
    public ActionResult MyController(){
        return RedirectToAction("MyAction","MyController",{Fecha=DateTime.Now});
    }
    public ActionResult MyAction(DateTime date){
        ModelPrueba model = new ModelPrueba(){Fecha=date};
        return View(model);
    }
}

When I call MyController Method, the Request.Params["Fecha"] is, for example: 30/12/2021 (dd/MM/yyyy).

But after RedirectToAction and it is executing MyAction Method, the Request.Params["Fecha"] has like value 12/30/2021 (MM/dd/yyyy)

Does someone knows what cause this format change and if is possible to not change the format?

I've already tried DateTime.ParseExact and it is not working neither.

It's like the RedirectToAction is generating the QueryString of the Request property of the class ControllerBase with another DateTime format.


Solution

  • you can use string class to prevent these type errors.

    public class MyController:Controller{
        public ActionResult MyController(){
            return RedirectToAction("MyAction","MyController",{ Fecha = DateTime.Now.ToString("dd/MM/yyyy")});
        }
        public ActionResult MyAction(string date){
            ModelPrueba model = new ModelPrueba(){ Fecha = DateTime.ParseExact(date, "dd/MM/yyyy", new CultureInfo("tr-TR")) };
            return View(model);
        }
    }