-2

I have done this to build JavaScript Arrays from int, double and string lists.

public string listToJsArray<T>(List<T> cslist)
    {
        bool numeric = true;
        if(
            !(typeof(T)==typeof(int)
            || typeof(T) == typeof(string)
            || typeof(T) == typeof(double))
            )
        {
            throw (new ArgumentException(message: "Only int, double and string are supported"));
        }
        if(typeof(T)==typeof(string))
        {
            numeric = false;
        }
        string JsArray = "[";

        for(int i=0;i<cslist.Count;i++)
        {
            string dataWithSurrendings = cslist[i].ToString();
            if(!numeric)
            {
                dataWithSurrendings = "'" + cslist[i].ToString() + "'";
            }
            if(i !=0)
            {
                dataWithSurrendings = "," + dataWithSurrendings;
            }
            if(i +1==cslist.Count)
            {
                dataWithSurrendings = dataWithSurrendings + "]";
            }
            JsArray += dataWithSurrendings;

        }

        return JsArray;
    }

My problem is when a list of strings is passed, apostrophes turn into &#39;.

for example, a list of {"1","2","3","4","5","6","7"} becomes this: [&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;1&#39;,&#39;6&#39;,&#39;7&#39;]

What modification is needed in this function, to return a correct array in JavaScript?

None of solutions did solve the problem. With JsonConvert I get almost same result. The problem is the single or double quote in View editor have not the same encoding as CS string.

user229044
  • 232,980
  • 40
  • 330
  • 338
FarhadGh
  • 134
  • 11

1 Answers1

1

I'm assuming that you are doing this to drop into a webpage somewhere, something like:

<script>
    @{
        var output = listToJsArray(Model.SomeList);
    }
    var myArray = @Html.Raw(output);
    // some Javascript using that array
</script>

Don't waste your time trying to do it yourself. It's a pain and you are reinventing the wheel. JSON is valid Javascript and a serialization of an array into JSON is absolutely identical to a Javascript array literal. So use Javascript. JSON.Net is really useful here:

<script>
    @{
        var output = Newtonsoft.Json.JsonConvert.SerializeObject(Model.SomeList);
    }
    var myArray = @Html.Raw(output);
    // some Javascript using that array
</script>

The serializer will handle all the annoying escaping, special characters and edge cases for you.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171