0

can somebody please tell me the difference if i do in my ActionResult

in this case

var transAcc= "SomeListHere";
var  v = new JavaScriptSerializer().Serialize(transAcc);
return Content(v);

and

var transAcc= "SameListHere";
return Json(new {list=transAcc });

2 Answers 2

3

The difference is that in the first case you are not setting the Content-Type response header to application/json while in the second this is done.

In first case the response is plain text and looks like this:

"SomeListHere"

And the Content-Type header is set to text/html which is incorrect as this is not HTML. It's text/plain. That's not even a valid JSON string.

In the second case it is a JSON string which looks like this:

{"list":"SomeListHere"}

Also in the first code example you are manually performing the JSON serialization which is plumbing code and should not be done in a controller and should be externalized in a custom ActionResult which is exactly what the creators of the ASP.NET MVC framework have don for you in the face of JsonResult which is your second code example.

Conclusion: if you want to send a JSON serialized representation of some model to the client always use the second approach.

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

2 Comments

"SomeListHere" is a SelectListItem i just added the "someListHere" for simplification .... is it still the same
@john, well a SelectListItem serializes differently in JSON but there still will be the difference as in the second example you are using the list property. You should use the second example as it sets proper Content-Type header.
1

None. Second one uses the first one. But I find the second more readable.

Here is the code behind JsonResult's ExecuteResult (using reflector) which is used in your second case:

public override void ExecuteResult(ControllerContext context)
{
    .... // some stuff
    if (this.Data != null)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        response.Write(serializer.Serialize(this.Data));
    }
}

UPDATE

Darin's response is correct although mine showing internals of the second.

Comments

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.