TimK TimK - 3 months ago 7
Javascript Question

How to create jQuery array from c# variable from SQL SELECT query

when my page loads I run a SQL SELECT to get a c# variable

var row = db.QuerySingle(myquery, someID);
var positionTags = row.PosTag;


the result is in the form:

"tag1,tag2,tag3,..."


I'm try to get this to a jquery Array with elements separated by the commas with the following

var positionTagsJS = ['@positionTags'];


however positionTagsJS shows up as an array with just 1 element.

tag1,tag2,tag3,...


I also tried to create an array from my initial c# variable as follows:

Array positionTagsArray = positionTags.Split(',');
positionTags = new JavaScriptSerializer().Serialize(positionTagsArray);


This leaves me with something in the form:

"[\"tag1\",\"tag2\",\"tag3\",\"...\"]"


and when I run it through my script

var positionTagsJS = ['@positionTags'];


I get...

["tag1","tag2","tag3","..."]


So, what is the most efficient way to get a java script and/or jQuery array of the form

["tag1","tag2","tag3","..."]

It probably doesn't matter but ultimately this array will be used to activate a jQuery UI selecatables widget.

Answer

I would do the second option, but assign the value like this:

var positionTagsJS = @Html.Raw(positionTags);