6

When passing js Date objects to my ASP.NET Web Api controller, I always get null. I have tried passing strings, array of string, timespan - all those works, except Date. When inspecting the request, the date is passed like this:

date:"2014-03-13T15:00:00.000Z"

In angular:

$http({ 
    method: 'get', 
    url: 'api/stuff', 
    params: {
       date: new Date()
    }
);

In my ApiController:

public IEnumerable<StuffResponse> Get(
    [FromUri] DateTime? date
){ ... }

What is the correct way to pass dates?

2 Answers 2

13

This works for me:

$http({ 
    method: 'get', 
    url: 'api/stuff', 
    params: {
       date: $filter('date')(new Date(), "yyyy-MM-dd HH:mm:ss")
    }
);
Sign up to request clarification or add additional context in comments.

Comments

1

The formatting of the date in your Javascript is not compatible with .NET DateTime parsing. See here for valid formats.

http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

4 Comments

either use a different format like @Rondles is saying or just take it in as a string and parse it using DateTime.Parse
when sending the js date through postdata, .NET manages to create a DateTime - so I guessed it would work when using get and params also..
The format of the date ("2014-03-13T15:00:00.000Z") is exactly the same for $http post data and get params, but the ApiController doesn't manage to recognize the string as a DateTime for get params.
I would suggest that you try SnareHangers approach and before you send it, convert it into a .NET recognised format. If it still doesn't work then you have a different problem. If it does work then the current formatting combined with this type of AJAX request is causing the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.