Question

I am trying to model bind a string passed in via a URL to a parameter in an action in my controller.

e.g. http://www.example.com/Controller/Action/2013-10-04/

where my Action method is

public ViewResult Action(DateTime dateTime) {
  //some logic
}

and my route mapping is

routes.MapRoute("Example", "Controller/Action/{dateTime}/", new { Controller = "Controller", Action = "Action" });

The URL specified above works, and dateTime is populated correctly with the date, and time of 00:00:00. However I want to define a time as well, but I am unsure what the format should be, and anything else I try then fails to modelbind the dateTime parameter at all.

Is this even possible with the built in ModelBinding or will I need to create a custom model binder?

Was it helpful?

Solution

It turns out it is just a case of passing in the date-time string as usual (e.g. 2013-09-23T16:47:00) in the URL, but you need to add requestPathInvalidCharacters to httpRuntime in web.config, i.e.:

<httpRuntime requestPathInvalidCharacters="">

so that the colons in the date-time string don't cause the A potentially dangerous Request.Path value was detected from the client (:). error to occur.

This is a bit unsafe though, so alternatively you can pass your parameter through in the query string and they will model bind correctly that way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top