0

I am working in asp.net 1.1 site.

My requirement is : On post back I have some data, which I want to store in some variable. And in javascript i want to add those info to a drop down list.

Ex :

The data coming from post back call is :

Text        Value
One             1
two             2
three           3

I want to store them in some variable and assign them to a drop down list in JAVASCRIPT based on a condidtion.

The code I am using to keep the value in C# is:

StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var test = [];");
for(int i=0; i < Engine.Length; i++)
{
    sb.Append("var obj = {text:" + Engine[i][0] + ","  + "value:" + Engine[i][1] +"};");
    sb.Append("test.push(obj);");
}
sb.Append("</" + "script>");

this.RegisterStartupScript("ownHtml", sb.ToString());

And adding the value to drop down list in JAVASCRIPT as:

for (var count = 0; count < test.length; count++)
{
    dlEngine.options[count] = new Option(test[count].text, test[count].value);
}

But it is not working.

1
  • What error do you get? And why are you declaring obj multiple times? Commented Aug 28, 2013 at 7:32

2 Answers 2

1

Besides @i100 's answer, also need to modify the server side code, you've missed the quotes.

sb.Append("var obj = {text:'" + Engine[i][0] + "',"  + "value:" + Engine[i][1] +"};");
Sign up to request clarification or add additional context in comments.

1 Comment

Plus don't forget to escape properly otherwise this is an injection attack - what happens if (somehow) one of your values contained quotes? Imagine this if the value was Something'};alert('security fail');//... You'd get var obj = {text:'Something'};alert('security fail');//... See the answers here for some solutions
0

instead of for (var count = 0; count < test.length; count++)

{
    dlEngine.options[count] = new Option(test[count].text, test[count].value);
}

use something like

for (var count = 0; count < test.length; count++){
    var opt = document.createElement('option');
    opt.value = test[count].value;
    opt.innerHTML = test[count].text;
    dlEngine.appendChild(opt);
}

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.