MVC : using Json pass datetime value

Posted in on 4/1/2014

If I set my controller's parameter as datetime type, is it gonna work? The answer is depend on what you gonna to pass. If value could be empty, correct date(like 2011/01/21), not date type (like 'hello'). You could add nullable to your controller's parameter (like DateTime?). Since if you passing empty or not datetime type, .net will throw exception before execute controller, it's better to use DateTime?. However, if you have to get the value. For example if you passing 20110101, so far, .net wouldn't assume that datetime type, so you'll get null value at C# code, but, if client could passing that kind of value and you want to handler it successfully, then, you shouln't use DateTime type at C# code and should use string type.

1. Controller

add DateTime type to your paramter

2. sample Html

3. Sample Javascript

4. error

So, if you complete steps from 1 to 3, and imprement your page, and passing empty value or value are not date type. You would see following error.

5. what's should you do!?

I tested two case, both are nullable and not nullable. So, if your business rule is, from client side, you allow valid date type (2011/01/02), and if it's not valid type, you assume that're null.Then, you could use Nullable DateTime type.(this one, since .net already convert from to your C# DateTime?, you don't need to convert to DateTime again). But, if your business rule is, want to handler more, you should use string type, and convert string to dateTime at your C# code.