Search code examples
javascriptasp.netwebmethod

Calling Web Method using Javascript on dynamically created Control


I am creating some controls dynamically in these Dynamic control there is <asp: Image> Control I want to call webmethod when I click that Image control.I searched a lot but nothing is happening.

the code for Dynamic control is

for (int i = 0; i < SearchResult.Length; i++)
        {
            System.Web.UI.HtmlControls.HtmlGenericControl panel = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
            panel.Attributes["class"] = "panel";
            panel.ID = "panel_" + (i + 1).ToString();
            System.Web.UI.HtmlControls.HtmlGenericControl inside = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
            inside.Attributes["class"] = "inside";
            Image img = new Image();
            img.ImageUrl = SearchResult[i].ImageUrl;
           // img.Attributes.Add("onclick", THE WEB Method I want to call);
            inside.Controls.Add(img);
            Label label = new Label();
            label.Text = SearchResult[i].Title;
            label.Font.Size = 10;
            label.Font.Bold = true;
            panel.Controls.Add(label);
            panel.Controls.Add(inside);
            test.Controls.Add(panel);
        }

and my web method is

[WebMethod]
    public static void AddToDownload(String ConnectionString,String Query)
    {
        SqlConnection con = new SqlConnection(ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand(Query, con);
        cmd.ExecuteNonQuery();
        con.Close();
    }

Solution

  • Get rid of the "onclick" line and wire up a server-side Click event, like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        var img1 = new ImageButton
            {
                ID = "ImageButton1", 
                AlternateText = "Button 1"
            };
        img1.Click += img_Click;
        Panel1.Controls.Add(img1);
    
        var img2 = new ImageButton
            {
                ID = "ImageButton2", 
                AlternateText = "Button 2"
            };
        img2.Click += img_Click;
        Panel1.Controls.Add(img2);
    }
    
    private void img_Click(object sender, ImageClickEventArgs e)
    {
        var whoClicked = (sender as ImageButton).ID;
    }
    

    I have changed your Image server controls to ImageButton server controls to more easily accommodate the Click event.

    Each of the two buttons is wired up to a common event handler and then in the event handler it is casting the sender (the control that initiated the event) to an ImageButton and then grabbing its ID to distinguish between the two buttons. You would want to put a null check there in case something besides an ImageButton initiates a click event.

    Let me know if you need anything clarified or have further questions.