2012-12-12

Web Api: Passing a Complex type in JSON

,

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.


 


image


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.

42 comments:

  1. for example perusing progressively books, getting right here on the styles of other awesome scholars or expounding on things that you such as.

    ReplyDelete
    Replies
    1. This is a great post ! it was very informative. I look forward in reading more of your work. Also, I made sure to bookmark your website so I can come back later. I enjoyed every moment of reading it.
      does garcinia cambogia extract work | does green coffee bean works | raspberry ketones

      Delete
    2. A big thank you for your post.Really looking forward to read more. Really Great.
      | Garcinia Cambogia German | Raspberry ketone Side Effects |

      Delete
  2. This article is full of passion; reading between the lines can appreciate the small of affection ... full-text level of clarity, smooth statement, exam dumps, It’s a quite interesting and different post. Keep posting. Stay blessed!!

    ReplyDelete
  3. Thanks for an insightful post. These comments are really helpful. I found a lot of useful tips from this post.74-344, LOT-403, 74-343
    and more detail.

    ReplyDelete
  4. I had the exact same problem, and copied part of your solution, data: JSON.stringify(new MyComplexType()), however "ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());" was not required as the JSON provider is enabled by default.

    ReplyDelete
  5. I usually commit those mistakes especially when in front of the computer where I don’t really think of anything else but what’s on the screen.thnx



    reviews on raspberry ketone |reviews on garcinia cambogia
    reviews on green coffee extract |reviews on green coffee bean

    ReplyDelete
  6. I know your blog now, and I loved the content! very useful, will continue being a reader, Thanks for the info!
    Imported Cars in Pakistan | Used Toyota Invincible in Pakistan | Used Lexus in Pakistan | Used Toyota Pirus in Pakistan

    ReplyDelete
  7. It’s appropriate time to make some plans for the future and it is time to be happy. I have read this post and if I could I wish to suggest you few interesting things or advice.
    David

    ReplyDelete
  8. Keep Looking for something more that uplift my mind capability. Keep it up.

    ReplyDelete
  9. wonderful issues altogether, you simply won a new reader.You write very well which is amazing. I really impressed by your post.Please keep writing as I want to learn more Home page

    ReplyDelete
  10. Thanks. I always enjoy reading your posts - they are always humorous and intelligent.I am a china tour lover,You can learn more: China tours | China Travel Agency | Customized China Tours

    ReplyDelete
  11. Most people have no concept of how an automatic transmission works, yet they know how to drive a car. You don't have to study physics to understand the laws of motion to drive a car. You don't have to understand any of this stuff to use Macintosh.villa mykonos

    ReplyDelete
  12. Although writing this kind of formula, first thing it is best to accomplish would be to define this issue. It is vital that you've a certain as well as specific pregnancy in the concept before commencing best paper writing service internet writers. Numerous themes usually are so quick that you might start writing promptly.

    ReplyDelete
  13. That’s been one of my mantras – focus and simplicity. Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.Lush Five

    ReplyDelete
  14. My business is extremely loved due to this blog. The a informative subject matter. This support us very much to fix a few problems. The opportunity are generally therefore excellent in addition to doing work style therefore quick. I do think it usually is support everyone. Cheers For more info Click on Chicago Limousine Services

    ReplyDelete
  15. Assortment is often a sincere and also secret London companion agency gives authentic London escorts young ladies with regard to guys involving taste.for more info see Car dealer Tampa

    ReplyDelete
  16. I am very interested for this post. This is by far one of the most good posts I read here and look forward for more such nice post.
    http://www.chansports.com

    ReplyDelete
  17. This article is something that will help me with my class assignment. It helped me to better understand another aspect of this topic. Thanks.

    Nfl Free Stream Online | Nhl Free Stream Online | football free stream online | Nba Free Stream Online

    ReplyDelete
  18. This is a terrific article, and I would like more information if you have any. I am fascinated with this topic and your post has been one of the best I have read. What are raspberry ketones | how to use garcinia cambogia

    ReplyDelete
  19. This is one of the great post I ever love to read.Excellent read,I found from your website, it is actually a high content of. power-graphics.com

    ReplyDelete
  20. This can be a great sound judgment post. Worthwhile one who is merely seeking the means relating to this element. It's going to undoubtedly help teach me personally. Bigcommerce Offer App

    ReplyDelete
  21. This can be a great sound judgment post. Worthwhile one who is merely seeking the means relating to this element. It's going to undoubtedly help teach me personally. Anthony Ammerman

    ReplyDelete
  22. This is a really cool blog. I am a frequent visitor of this site. Read the news on the earthquake. It was really sad news. Keep posting more such information’s. All the very best to you and your team. Good luck. You can try to get zanzibar hotels

    ReplyDelete
  23. You could post on the samples for the blog. You may distribute it's priceless. Your blog critiquing should heighten your clicksHoward Davidson Arlington

    ReplyDelete
  24. This is usually a good appear wisdom post. Worth it individual who is only in search of this indicates concerning this element. It is going to unquestionably assist instruct myself. Fore more information visit on houlton institute

    ReplyDelete
  25. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, Spesenabrechnung

    ReplyDelete
  26. You may write about the special offers on the blog. You could speak it's electrifying. Your blog studies might expand your paymentsmykonos villa

    ReplyDelete
  27. Hello Sir
    Thank you very much for giving good instructions. I think it is a best thing like a sell structured settlement . Both are equal.

    ReplyDelete
  28. Today's Senate Commerce hearing on the awful Marketplace Fairness Act, a bill the likes of which we've been crusading against for more than a decade now, was a comedy of errors that would have been funnier if it weren't so sadafrodisiacos naturales

    ReplyDelete
  29. we will make sure that it's available for customers who want to look at new functionality. It certainly is a high priority for us and we're looking at it for a future release.Spread Betting Forum

    ReplyDelete
  30. Crowded classes with insufficient supporting materials would make the programmed ineffective and hence would not produce the expected outcomes. Yacon Root

    ReplyDelete
  31. Fantastic article and it is very helpful. Thank you very much

    ReplyDelete
  32. Most of us may guarantee that it truly is intended for clients Wholesale duvet covers who wish to check out brand-new operation. It really is a superior top priority for people like us and also we have been investigating this for any future discharge.

    ReplyDelete
  33. I am very interested for this post. This is by far one of the most good posts I read here and look forward for more such nice post.Buy Wholesale Bed Linen Online

    ReplyDelete
  34. I am very interested for this post Thanks for taking the time to discuss.I enjoy the information you provide..

    Captain America Leather Jacket

    ReplyDelete
  35. many of us will certainly make certain that it truly is for consumers who wish to examine new performance. It is a high main concern for people in addition to we've how to make apple passbook been looking at that for a upcoming generate.

    ReplyDelete
  36. The issue is an issue that not enough folks are speaking intelligently about. I am very glad I staggered across this. I will pass on your blog to all my friends.

    ReplyDelete
  37. For instance in the seven wastes, Overproduction is often considered one of the worst wastes because it creates most of the others. Hotel Towels in Bulk

    ReplyDelete
  38. I really love your article. It is good and useful. share we keep in touch more about your post on AOL? I require an expert on this house to unravel my problem. May be that’s you! Taking a look ahead to look you.Franchises UK

    ReplyDelete
  39. financial plan will give you a blueprint directing you towards achieving your goals, what products you should be investing in, for what time period you should invest for, whilst considering your constraints such as your attitude towards risk.electronic cigarettes

    ReplyDelete