In my 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
Server Side code
public class ValuesController : ApiController
{
Server Side code
public class ValuesController : ApiController
{
public class MyComplexType
{
public string Name { get; set; }
public MyComplexSubType MyComplexSubType { get; set; }
}
public class MyComplexSubType
{
public int Age { get; set; }
}
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post(MyComplexType value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
THE MISSING LINK You need to be Add
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());
Html Page
<input type="button" name="test" title="test" onclick="GeneralPost();" />
script
<script type="text/javascript">
function GeneralPost() {
var dataJSON = { FirstName: 'dd', LastName: 'dd' };
var value = {};
value.FirstName = "test";
value.LastName = "lasttest"
jQuery.support.cors = true;
debugger
$.ajax({
url: 'http://localhost:29793/api/Values',
type: 'POST',
async: true,
cache: false,
data: dataJSON,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: SendComplexTypeCallBack
});
}
function SendComplexTypeCallBack(data) {
alert("Complex type sended");
}
</script>
Happy coding .......
Out Put :
Reference urls
http://www.codeproject.com/Articles/424461/Implementing-Consuming-ASP-NET-WEB-API-from-JQuery
Comments
Post a Comment