Passing a DateTime parameter to an MVC Action

Passing a DateTime parameter to an MVC Action

If you need to pass a date to an MVC action method you should include it in a form and pass back the entire form as a single class.

If for some reason this can't be done and you have a method with a signature similar to

public class MyController
{
public void MyAction(int id, DateTime date)
}

it can be called in a view using something similar to

@{
int id = 0;
DateTime date = DateTime.Today;
}
@Url.Action("MyAction", "MyController", new {id, date})

This will create a URL along the lines of
/MyController/MyAction?id=0&date=SomeSerializedEquivalentOfDate

The default MVC DateTime binding is NOT culture aware so depending on your current culture settings it may serialize the date as dd-MM-yyyy, MM-dd-yyyy or any other format.
When the ModelBinder attempts to deserialize this to a DateTime it knows nothing about the culture it was serialized under so someone who selects a date of January 4th may find that the server thinks they selected April 1st.

There are a number of possible solutions than could be implmented quicker than a custom DateTime binder;

  • A Culture Invariant serialization of the DateTime
@Url.Action("MyAction", "MyController", new {id, date.ToString("o")}) // ISO date format
  • Convert the DateTime to ticks and post that as a number
public class MyController
{
    public void MyAction(int id, long ticks)
    {
    DateTime date = new DateTime(ticks);
    }
}

@Url.Action("MyAction", "MyController", new {id, ticks = date.Ticks})

Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to SimonReynolds.ie
Great! Next, complete checkout for full access to SimonReynolds.ie
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.