3

Trying to return this list as an array so I can then grab it on the client side via JS and iterate through its values.

So one of my .ashx methods returns a list like this in the end of the method:

equipmentTypes is a generic list of strings

        _httpContext.Response.ContentType = "text";
        _httpContext.Response.Write(equipmentTypes.ToArray());

When i receive it on the client, I get the literal text "System.String[]". So what content type should I return? Obviously this is not correct.

Then I assume I can eval this into an array (object) on the js side.

3 Answers 3

4

You should use JSON when sending data to javascript. You SHOULD NOT use eval as this opens you up to many security vulnerabilities (i.e. XSS).

See this article for more on C# and JSON, including turning a C# array into JSON.

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

Comments

1

You should serialize the objects that you wish to write to the response stream as JSON, the content-type of which is application/json. You could either use the built-in DataContract serialization or a third-party open source library such as the NewtonSoft JSON.Net library.

On the client you should use JSON.parse rather than eval.

Comments

0

On the server side you can generate JSON using the built-in JavaScriptSerializer:

var js = new System.Web.Script.Serialization.JavaScriptSerializer();
_httpContext.Response.ContentType = "application/json";
_httpContext.Response.Write(js.Serialize(equipmentTypes.ToArray()));

And on the client you can use JSON.parse (supported by all modern browsers) to get an array back. eval is not really a security risk when you are in control of both client and server, but it's still the wrong tool for the job.

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.