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.

106 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
    3. thanks for the post. also found some good post relating to this in www.programmerguide.net check if it is useful for you

      Delete
    4. refer the site ProgrammerGuide.Net for programming guides

      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. Keep Looking for something more that uplift my mind capability. Keep it up.

    ReplyDelete
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. Crowded classes with insufficient supporting materials would make the programmed ineffective and hence would not produce the expected outcomes. Yacon Root

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

    ReplyDelete
  27. 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
  28. 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
  29. 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
  30. 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
  31. 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
  32. 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
  33. 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
  34. 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
  35. I have read your post about Restoring Navigation Links in the Header Menu of SharePoint, this is very informative post really like it a lot.Thanks for sharing the post.Pest Control

    ReplyDelete
  36. I have been itching my thinker past this point, beside forward We've noticed considerably inconsistency "rescue" on the tangle... So Pronto i am merely publishing that underneath along accompanying suppose peoples volition determine that.catamaran charter yachts

    ReplyDelete
  37. Happy to see your blog as it is just what I’ve looking for and excited to read all the posts. I am looking forward to another great article from you. bowtrol

    ReplyDelete
  38. i used to be appreciating viewing personnel seven days every week. Once regarding for my state of affairs bought a complete smaller from their website...new york motorcycle insurance

    ReplyDelete
  39. The only sad part about moving away from Maryland recently, was having to leave ProFIT. Now in my search for a new Zumba class, I am very nervous about what I will find. Alex set the bar very high and now I am expecting, and hoping to find, the same crazy fun she brings to her classes.recuperar dados

    ReplyDelete
  40. Just to add, we could really help share your posts and your website further. Let us know if we can be of help. loção anti queda

    ReplyDelete
  41. Thorough examples, though I'm not getting the results I'm supposed to get.
    My problem is with sending complex types as JSON. If I use JSON.stringify on the client side, all the field values are received as null/empty/0 on server side. Without JSON.stringify (if I only send the JS object), I only get the simple fields (not the 2nd tier fields as well).
    Anybody have any suggestions?

    ReplyDelete
  42. Ashok Jhunjhunwala, what works for one industry, such as utility or smart metering may not work for retail. So the service providers have to be very careful when they are addressing a particular segment. best dentist in plano

    ReplyDelete
  43. The is attractive judge viewpoint is at possibilities with other
    saltmate salt cell

    ReplyDelete
  44. Thanks for taking the time to share this,Great blog post. Thanks for taking the time to share this,Great blog post.

    ReplyDelete
  45. This is a very useful publish. A lot of individuals probably have been awaiting this type of a publish from this website. Projects which can be seen by whole categories, exactly the type of service we required to link.www.wizpromos.com

    ReplyDelete
  46. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.Jobs in UAE

    ReplyDelete
  47. have an experience with the students who took advice regarding the SAT score. If someone sets a target for the Harvard then an acceptable score is achieved. Vapor High USA

    ReplyDelete
  48. I am getting this error : No 'Access-Control-Allow-Origin' header is present on the requested resource.

    ReplyDelete
  49. The Singing will be one of the most original classes Pillars of Eternity and seems to stand midway between the traditional concepts of the Shaman and the Bard.baltimore pest control

    ReplyDelete
  50. have an experience with the students who took advice regarding the SAT score. If someone sets a target for the Harvard then an acceptable score is achieved. Vapor High USA Buy Facebook Likes

    ReplyDelete
  51. I have read your excellent post. This is a great job. I have enjoyed reading your post first time. ferienwohnung usedom

    ReplyDelete
  52. Thank you for the solution. This post will help a lot of programmers who are having similar problems. Thank you for your post.
    Selling the grass reinforcement mesh in UK

    ReplyDelete
  53. This is a very nice solution. This post would help a lot of programmers who are having similar problems for a long time. Thank you for your post.
    Horse mats

    ReplyDelete
  54. The solution that you have provided will certainly help many coders to understand where the problem was. Thank you so much for sharing this wonderful piece.
    gymnastic mats

    ReplyDelete
  55. You have done a great job in finding solution. Thank you so much.
    garage flooring

    ReplyDelete
  56. There is no doubt this will get you amp’d up for a good weightroom workout. This is the 2nd edition of Brian Eno’s art software project.Swarovski 2014 Crystal Snowflake Ornament

    ReplyDelete
  57. Thank you with regard to finding the time to debate this, I am powerfully over it in addition to love learning far more with this topic. If at all possible, because you gain know-how, can you intellect changing your website with an increase of information?Change Management Models

    ReplyDelete
  58. Thank you with regard to finding the time to debate this,I am powerfully over it in addition to love learning far more with this topic.You guys shared a great work.Thanks for sharing a great post.Keep it up.

    ReplyDelete
  59. Personal injury law is a difficult field to get a case fought in. That means you should only an experienced lawyer. Look for a lawyer with a great track record so you give yourself the best advantage.
    86620000.com |

    beatsbydrecybermonday.com |

    dapoxetinebuynow.com |

    fioricetdirect2k.com |

    firstantidepressant.com |

    jsntcj.com |

    youngsmhs.com |

    michaelkorswatchhandbagssale.com |

    nike4freerun.com |

    pompeachaleurdevis.com |

    ReplyDelete
  60. This comment has been removed by the author.

    ReplyDelete
  61. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post.mollify.biz

    ReplyDelete
  62. This is a great informative blog by you guys on data base.I am happy to find your distinguished way of writing the post.

    ReplyDelete
  63. This is a great blog.A great information in the blog.Data base is a good to study and other maters so you guys done great work.Keep it up.

    ReplyDelete
  64. Thanks for a wonderful share. Your article has importaciones your hard work and experience you have got in This field. Brilliant reading .I love it.limo rental Queens

    ReplyDelete
  65. A resume plays an important role in getting job.Seek help from resume writing service will help you to compose a resume with best resume format as per job needs.

    ReplyDelete
  66. Once you are well-informed about the real estate market and the selling process, selling your own home will become less stressful. Knowing how to navigate your way through this process is a wonderful skill.bus rental Los Angeles

    ReplyDelete
  67. Really i appreciate the effort you made to share the knowledge. The topic here i found was really effective to the topic which i was researching for a long time.plantation auto accident attorney

    ReplyDelete
  68. Oh! What a brilliant job you’ve accomplished here. All the facts on this topic are available in this post. I have not read any article up till now that tells every little fact about a certain topic. You must be very proud of yourself. Keep this up and you shall become the best writer ever!Bridal hairstyles half up half down

    ReplyDelete
  69. The Usa offers a lot of choices which choosing it's possible to be difficult! Narrow lower your best choices as well as let your whole family choose.washing machine repairs

    ReplyDelete
  70. The Usa offers a lot of choices which choosing it's possible to be difficult! Narrow lower your best choices as well as let your whole family choose.Small Kids ATVs

    ReplyDelete
  71. The Usa offers a lot of choices which choosing it's possible to be difficult! Narrow lower your best choices as well as let your whole family choose.male enhancement vitamins

    ReplyDelete
  72. i love indian models in dubai. that provides best envirement for entertainment. you can b contact us +971561616995 adn visit this site
    Entainment in dubai

    ReplyDelete
  73. Lovely post. It gives a great insight. Well written.

    ReplyDelete
  74. Great post, Well said… and judging from the rest of the comments it is something that has generated great interest.

    ReplyDelete
  75. My good friend just sent me this article. Great read. How do I subscribe for more?

    ReplyDelete
  76. Fascinating insight. We would love to connect our website with yours - do let us know if it is of interest.

    ReplyDelete
  77. Have you been interested in procuring Android App Store ratings & reviews? If that's so, you’re on correct web page. We can easily present you genuine Android App Store reviews and ratings in bulk. buy appstore reviews

    ReplyDelete
  78. I thank you for sharing the ideas on how to solve problems with JQuery. These are very important tips and i really appreciate. If you are a student and may be you need Master’s Thesis Data analyzing assistance, we are a reliable site that you can rely on.

    ReplyDelete
  79. eaadhar

    Now instantly learn how to open or sign up for the social security my account and know the social security disability benefits
    and read the all information before give a apply for a disability insurance



    Need free beautiful calendar template and get the printable calendar free, for your office academic institution use then must visit and grab the calendars for every new year

    ReplyDelete
  80. We have escorts agency in Dubai. We also provided indian and pakistani escorts in dubai. Then contact us for more details.

    Indian Escorts in Dubai
    Pakistani Escorts in Dubai
    Escorts in Dubai

    ReplyDelete
  81. Mesmerized article written on this blog with other relevant information. It is straight to the point that how we can improve our skills as well as how we can be represented to a new stream of professionalism.
    วิธีการแทงบอลออนไลน์

    ReplyDelete
  82. That is such a wonderful and relevant information for me. I am recently start learn ASP.Net "MVC" Model View Controller this post is very helpful for me about Web API. I appreciate your content this is tremendous content for beginners. Thank you so much for share this knowledge in public.
    I must say that i am also working as a digital marketing expert in United Kingdom and best picture framing wanstead is my product, which is the one I am working on.

    ReplyDelete
  83. This is my second visit at your website thanks for sharing this information in public i really appreciate your content, keep it up. Website Development Companies

    ReplyDelete
  84. I am visiting your blog second time and must say that is such wonderful and informative content. Thank you so much for sharing in public. edward waite art galleries london

    ReplyDelete
  85. That is such a helpful post for MVC developer. Nice article, and thanks for share this post in public economy booking promo code

    ReplyDelete
  86. Buy Real and Fake Passport Online | Buy Fake ID Cards

    We are the world number one solution when it comes to the processing and production of documents online like passports, ID cards, driving license and many more documents. From our website you can able to buy real and fake passport online, Buy fake id cards online, buy fake certificates online, fake driving license online. WhatsApp now: 1(443) 351-8162

    For more details you can visit our website: https://buyalldocument.com/ OR Email us at buyrealfake.documents@yandex.com

    ReplyDelete
  87. Great knowledge, do anyone mind merely reference back to it web development company

    ReplyDelete
  88. Welcome to the beautiful world of Delhi escorts. Here you will get the most delicious and tempting Delhi escorts who are awaited so much to being physical with you. Yes, it is true just meet our Aerocity escorts girls, they are waiting to provide extraordinary service to you. Delhi Escorts is offering such beautiful and high-profile models available 24x7 hours for you.

    ReplyDelete
  89. JSON Formatter online tool to minify, beautify your json

    ReplyDelete
  90. Really great blog post. I read it very carefully. It is very informative. Really helpful and unique blog post. Looking For Social Media Service Click Here Get Social Media Marketing Services Online In UK

    ReplyDelete