1

Basically I'm creating divs on basis of a number. Here is where i'm creating these divs:

cssStyle.Attributes["href"]="Content/Options/"+(Global.NumberOfResponses).ToString() +".css";
string x = "<table class=\"Centralizetable\"><tr>";
for (int i = 0; i < Global.NumberOfResponses; i++) { 
    if(i==0){
        x = x + "<td><div class=\"leftmost\" onClick=\"myClickListener\" runat=\"server\"><img class=\"imageProps\" src=\"/Images/1.jpg\" id=\"imgChoice_" + i.ToString()+ "\" /><p class=\"optionText\">Good</p></div></td>";
    }
    else {
        x = x + "<td><div class=\"center\"  onClick=\"myClickListener\" runat=\"server\"><img class=\"imageProps\" src=\"/Images/1.jpg\" id=\"imgChoice_" + i.ToString() + "\" /><p class=\"optionText\">Good</p></div></td>";
    }
}

x = x + "</tr></table>";

multichoice.InnerHtml = x;

And it is supposed to call this function:

public void myClickListener(object sender, EventArgs e)
{
    Image A = sender as Image;
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('"+A.ID+"')", true);
}

But the dynamically created divs aren't clickable.

Bassie
  • 9,529
  • 8
  • 68
  • 159
saadwaqar
  • 33
  • 3

2 Answers2

0

You should try OnServerClick instead of onClick:

cssStyle.Attributes["href"]="Content/Options/"+(Global.NumberOfResponses).ToString() +".css";
string x = "<table class=\"Centralizetable\"><tr>";
for (int i = 0; i < Global.NumberOfResponses; i++) { 
    if(i==0){
        x = x + "<td><div class=\"leftmost\" OnServerClick=\"myClickListener\" runat=\"server\"><img class=\"imageProps\" src=\"/Images/1.jpg\" id=\"imgChoice_" + i.ToString()+ "\" /><p class=\"optionText\">Good</p></div></td>";
    }
    else {
        x = x + "<td><div class=\"center\"  OnServerClick=\"myClickListener\" runat=\"server\"><img class=\"imageProps\" src=\"/Images/1.jpg\" id=\"imgChoice_" + i.ToString() + "\" /><p class=\"optionText\">Good</p></div></td>";
    }
}

x = x + "</tr></table>";

multichoice.InnerHtml = x;

See MSDN and SO for more

Community
  • 1
  • 1
Bassie
  • 9,529
  • 8
  • 68
  • 159
0

If you look at the rendered HTML, you should see the [runat="Server"] attribute is being rendered. You are creating dynamic HTML, but its not processed as a server side control.

You can change the click event to call a JavaScript function or change they way you are creating the elements if you need to invoke a server call

see MSDN for how to programmatically adding controls

Steve
  • 1,995
  • 2
  • 16
  • 25
  • Thank you! Let me leave this here for others, This is how i achieved it: `x = x + "

    Good

    ";` ` function tempFunc(img) { alert($(img).attr('src')); } `
    – saadwaqar Jul 23 '16 at 20:03