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:
[code language=”csharp”]
public class CustomViewModel
{
public object CustomValue { get; set; }
}
[/code]
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:
[code language=”csharp”]
public class DateRange
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
[/code]
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):
[code language=”javascript”]
return $http({
method: ‘POST’,
url: "/api/updateCustomObject",
data: {
customValue: {
startDate: $scope.startDate,
endDate: $scope.endDate
}
}
});
[/code]
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):
[code language=”csharp”]
[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);
}
[/code]
And voila, you have the JSON data from AngularJS converted to a C# class object in WebApi. Hope this helps you. Happy Deserializing!
No Responses