How do I pass a datetime value as a URI parameter in asp.net mvc?

前端 未结 10 1057
孤城傲影
孤城傲影 2020-12-04 18:58

I need to have an action parameter that has a datetime value? Is there a standard way to do this? I need to have something like:

mysite/Controller/Action/2         


        
10条回答
  •  遥遥无期
    2020-12-04 19:29

    You should first add a new route in global.asax:

    
    routes.MapRoute(
                    "MyNewRoute",
                    "{controller}/{action}/{date}",
                    new { controller="YourControllerName", action="YourActionName", date = "" }
                );
    

    The on your Controller:

    
    
            public ActionResult MyActionName(DateTime date)
            {
    
            }
    

    Remember to keep your default route at the bottom of the RegisterRoutes method. Be advised that the engine will try to cast whatever value you send in {date} as a DateTime example, so if it can't be casted then an exception will be thrown. If your date string contains spaces or : you could HTML.Encode them so the URL could be parsed correctly. If no, then you could have another DateTime representation.

提交回复
热议问题