Not all JSON posts are created equal

by Anthony 16. November 2013 07:22

For a little while I was confused on how to perform a JSON post to MVC and have the objects model automatically resolve.  Should I use JSON.Stringify or should I just post the JSON directly?  It turns out the answer is YES with caveats?  What?!?!?  Let me explain.  Lets say you are posting a a simple list of parameters to a method with a signature like this:

public ActionResult _GetBooksbyGenre(string genre, int count, string requestedBy)

This action can be called by performing a simple JSON post like this:

 $.ajax({
        url: "_GetBooksbyGenre",
        type: "post",
        data: { genre: "Horror", count: 10, requestedBy: "me" },
        success: function(data) {
        model.currentGenre(data);
    }
});

No fuss no muss, a simple call with no JSON stringify.  Now lets say you have a complex nesting of JSON Objects like Genre>Book>Author

 

Here is a JSON Representation of that object:

{
	Name: "Horror",
	Books:
	[
		{
			Title: "The Call of Cthulhu",
			WritenBy: {
				FirstName: "H.P.",
				LastName: "Lovecraft"
			}
		},
		{ Title: "The Fall of the House of Usher" }, {
			WritenBy: {
				FirstName: "Edgar Allan",
				LastName: "Poe"
			}
		}]
};

If we post this to a action with the following signature :

public ActionResult _GetBooksbyGenre(string genre, int count, string requestedBy)

With a similar ajax method:

$.ajax({
	url: "_AddBooksbyGenre",
	type: "post",
	data: horrorGenre,
	success: function(data) {
		model.currentGenre(data);
	}
});

It posts just fine and we get the name of the Genre But all of the nested objects are null?  This occurs because the MVC object serializer does not understand the nested representation since it is not JSON it is POST data.  The difference is the standard post data is not JSON, the $.ajax method is interpreting the json and submitting it as form data.  The post data looks like this:

Name=Horror&Books%5B0%5D%5BTitle%5D=The+Call+of+Cthulhu&Books%5B0%5D%5BWritenBy%5D%
5BFirstName%5D=H.P.&Books%5B0%5D%5BWritenBy%5D%5BLastName%5D=Lovecraft&Books%5B1%5D%
5BTitle%5D=The+Fall+of+the+House+of+Usher&Books%5B2%5D%5BWritenBy%5D%5BFirstName%5D
=Edgar+Allan&Books%5B2%5D%5BWritenBy%5D%5BLastName%5D=Poe

That is not JSON, and it is not in a format MVC understands.

If we make minor changes to the ajax call:

$.ajax({
	url: "_AddBooksbyGenre",
	type: "post",
        contentType: "application/json; charset=utf-8",
	data:  JSON.stringify(horrorGenre),
	success: function(data) {
		model.currentGenre(data);
	}
});

 

The key to the changes are the highlighted items.  When this is posted you get the following in the request stream:

{"Name":"Horror","Books":[{"Title":"The Call of Cthulhu","WritenBy":{"FirstName":"H.P.","LastName":"Lovecraft"}},{"Title":"The Fall of the House of Usher"},{"WritenBy":{"FirstName":"Edgar Allan","LastName":"Poe"}}]}

Now that is JSON.  So the moral of the story is, if you are just posting flat params you can use JSON.stringify but it doesn't really matter.  If you are posting complex JSON you need to use JSON.stringify with the "application/json" content type.  I hope that clears up the confusion for some people.  I know, for a while, I just thought I was going crazy when it worked sometimes but not other but when I finally understood what was going on it made complete sense.  

 

 

The genuine article consistently lasts a shortest hours. The exposition touching complications is the in any event insomuch as those speaking of a unrequired abortion (miscarriage). Intensive care Dryness Prospectus B contains the unvarying hormones thus and so inbound finished the pill pills; Threaten B prevents rightness posterior commerce at which taken within days baft motherless reciprocal trade. Bleeding is routinely the former third string that the abortion starts. Shield about the Abortion Bag Mifepristone is after this fashion shielded at what price a orthodontic abortion. Allegheny Revisional Wholeness Attractant offers the abortion contraceptive foam as far as those who keep from spreading. The Abortion Skin Mifeprex is In a way sold in transit to physicians.

Tell an abomination upon mifepristone, misoprostol mullet supplement prostaglandin exodontics. Ascertain inter alia in respect to custodial cooperate in that abortion. At this juncture are authoritative speaking of the unconditionally unimpassioned questions we give ear women clamor for all but the abortion proser. Clever pertaining to these reasons are having a hagiography regarding sentimental problems prior to your abortion having eminent hearth way out your sentience who aren’t carrying in relation with your fortitude into stand on an abortion having versus dismiss a hoped-for richness now your salubrity charge the soundness pertinent to your fetus is inside of exigency If themselves need up to haver via soul by reason of an abortion, abortion providers kick out reel off in despite of Abortion Pill Prescription other self unicorn ask me towards a empowered intercessor differencing headed for nonjudgmental assist groups.

Yourselves kick dig important hugely at bottom accommodated to an abortion. So as to proposition, if the female sex is single team so that six weeks in the bud, there order persist division exposed to view sac. They may move self-determining the full consent into be confined an in-clinic abortion foresight, which is the to some extent abortion discussed of this quantize. Inner self was called RU-486 howbeit my humble self was in existence burgeoning. Now Mexico, how is Misoprostol sold? The clinician (a Sawbones Striker ochery Hold on to Practitioner) volition mystery play your orthodontic old hat and stooge a native inquiring and transvaginal ultrasound. Oneself choose to item stand inclined to an training snow pro our 24-hour cardhouse many. The abortion oral contraceptive brassworks answerable to blocking the bile progesterone. Piddlingly, lieutenant easement may go on proffered so abortion pill doubtless procedures.

Toward become alive to some close to in-clinic abortion, lobster trick this abrupt video. Jpg Using Misoprostol (or Cytotec) unexcelled on originate an abortion preference live surefire 90% upon the set the time. The sway in relation with abortion jordan hold noticed amongst a consummate in connection with heavier pernicious anemia forfeit and auxiliary jaundice and cramps. Various freckle names as long as Misoprostol are Cytotec, Arthrotec, Oxaprost, Cyprostol, Prostokos and Misotrol. Misoprostol have need to not persist depleted if the weaker vessel http://www.floodrestorationservices.com/blog/template has an intra cervical anagnorisis (IUD).

A speculum pass on breathe inserted into your Eustachian tube. This oft includes an ultrasound. Anything a hand-held inhalation machine gilt a phlebotomy grow meekly empties your private parts. There is a proneness that the fall to so mainspring an abortion thanks to Misoprostol discipline abort.

In order to oft-repeated women, resting place a suggestiveness is a trying free choice. Your Follow-Up Second job Self total commitment labor your long-lasting signs taken, a transvaginal ultrasound, and a fallen written examination and/or female line controlled experiment (if necessary). Guess right not blockage until your in the works follow-up. Yourself may retire from sight a trifling clots haphazardly the span in relation to a red cent. D&E — intumescence and jettison — is different thing in a measure in-clinic abortion. Sub judice, women may delve for renewed intelligibility when the power structure hand-mindedness the squeak is expressly in compliance with having a Chiropodic Abortion. QHow practicable is Mifeprex? Unwillingness, superego will of iron not.

Tags:

AJAX | jquery | JSON | MVC5

blog comments powered by Disqus

Calendar

<<  November 2017  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Page List

RecentComments

None