Felipe Pereira
Felipe Pereira

Reputation: 12320

MVC JSON data reference

there is a call to my controller where something like this is performed:

someObject.Name = "Mike";

JsonResult result = Json(new { TheMan = someObject }, JsonRequestBehavior.AllowGet);

someObject.Name = "Paul";

return result;

The problem is that when the client receives the data, the name is "Paul" when I was expecting that the result JSON was created with "Mike".

In the docs it says "The result object that is prepared by this method is written to the response by the ASP.NET MVC framework when the object is executed."

Is there a workarround where I can manipulate the objects used on the JSON data without being worried about changing the response? (Clone the someObject or something)

Thanks.

Upvotes: 2

Views: 213

Answers (1)

asymptoticFault
asymptoticFault

Reputation: 4529

You pretty much said it. When you create the Json object you are simply adding a reference to someObject so if you change the value it will be changed inside the Json object as well. The Json is not actually written to the response until the JsonResult is returned by the action. If you want to set the value to something else without affecting the original value you will need another copy of the object.

Upvotes: 3

Related Questions