Last Tuesday I had a challenging task. Pass a range of dates from AngularJS to WebApi as a single value, and more importantly, the value must be converted as a class instance. It might be simple for some of you but if you are under a bit of stress, it’s not. At first nothing was passing but don’t despair, I found a cure solution. First of all make sure that the Class fields are all objects (Not strings! Strings don’t work. That was the first mistake). So this was my new class:
public class CustomViewModel { public object CustomValue { get; set; } }
Then make a C# class that resembles the JSON object having the same number of fields with same names. Please note that JSON field names will probably start with a lowercase letter. In C# you can still define the fields in Camel Case as follows:
public class DateRange { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } }
Now it’s time to pass the object from AngularJS to our ‘UpdateCustomObject’ method in WebApi (I used the post method using the $http injector in Angular):
return $http({ method: 'POST', url: "/api/updateCustomObject", data: { customValue: { startDate: $scope.startDate, endDate: $scope.endDate } } });
In the UpdateCustomObject method in C#, the customValue is stored as an object. What is needed now is to deserialize the ‘CustomValue’ object to the type that I want it, in my case the ‘DateRange’ class. In the next code snippet, I’m using the JsonConvert method found in the Newtonsoft library (make sure you add ‘using Newtonsoft.Json;’ at the top of the class):
[HttpPost, ActionName("updateCustomObject")] public HttpResponseMessage UpdateCustomObject([FromBody]CustomViewModel viewModel) { if (!ModelState.IsValid) return new HttpResponseMessage(HttpStatusCode.BadRequest); // convert custom value to DateRange viewModel.CustomValue = JsonConvert.DeserializeObject<DateRange>(viewModel.CustomValue.ToString()); //////////////////////////// // save to database //////////////////////////// return new HttpResponseMessage(HttpStatusCode.OK); }
And voila, you have the JSON data from AngularJS converted to a C# class object in WebApi. Hope this helps you. Happy Deserializing!