In one project i wanted to pass a complex type to the Post method of an Web Api controller. The Post itself will be done using JQuery in the JSON format. I noticed that the parameter was always null. After a bit of searching i found the solution.
The Set Up
Server side
public class ValuesController : ApiController
{
// POST api/values
public void Post(MyComplexType value)
{
}
}
public class MyComplexType
{
public string Name { get; set; }
public MyComplexSubType MyComplexSubType { get; set; }
}
public class MyComplexSubType
{
public int Age { get; set; }
}
Client Side
<script type="text/javascript">
function MyComplexSubType()
{
var self = this;
self.Age = 26;
}
function MyComplexType()
{
var self = this;
self.Name = "Kenny Tordeur";
self.MyComplexSubType = new MyComplexSubType();
}
function PostComplexType()
{
$.ajax("/api/values", {
data: JSON.stringify(new MyComplexType()),
contentType: 'application/json',
type: 'POST',
success: SendComplexTypeCallBack
});
}
function SendComplexTypeCallBack(data)
{
alert("Complex type sended");
}
</script>
The PostComplexType will be trigged by a click event on a button. It will create a javascript object called MyComplexType. This object will map directly to the object we created on the server side.
The missing link
With this set-up the parameter will always be null. We need to add a line of code to the global.asax.
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
Value providers are used by the model binding system in MVC to populate the values of model objects. We basically add a provider that enables to bind a model to a JSON model. The solution can be downloaded here.