2

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I end up creating a new cloned "someObject" for the JSON, since it seems that there is no option to "freeze" the JSON when declared. I'll wait a couple of days to check this one as the correct answer, just to let/encourage anyone propose something else.
Fair enough. It's just the way the language works and pretty much any language really.
It also depends on the behavior of the created object (class A), if its constructor receives another object A(B b) and use it to set its own properties "this.Name = b.Name;", when B.Name is updated nothing will happen to A.Name
Right because those are two different variables or properties on the same object; updating one will of course not affect the other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.