0

I have an asp.net application in which i have to call a javascript function when an event is fired .I tried this :

protected Consultation controlconsultation  = new Consultation();
 protected void Page_Load(object sender, EventArgs e)
        {

           controlconsultation.imageinfo += controlconsultation_imageinfo;
           Session["controlconsultation"] = controlconsultation;
       }

        void controlconsultation_imageinfo(object sender, CommandEventArgs e)
        {String csName = "myScript";
            Type csType = this.GetType();

            // Get a ClientScriptManager reference from the Page class.
            ClientScriptManager cs = Page.ClientScript;

            // Check to see if the client script is already registered.
            if (!cs.IsClientScriptBlockRegistered(csType, csName))
            {
                StringBuilder csText = new StringBuilder();
                csText.Append("<script type=\"text/javascript\"> ");
                csText.Append("alert(" + "Espace_Candidat/InfoEdition.ascx" +"); </");
                csText.Append("script>");
                cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
            }
        }

Code behind of the user control

public event CommandEventHandler imageinfo ; 
protected void Page_Load(object sender, EventArgs e)
        {
 Consultation current = (Consultation)Session["controlconsultation"];
                imageinfo = current.imageinfo;
       }
  protected void Valider (object sender, CommandEventArgs e)
          {
            if (imageinfo != null)
              {
                  string pageNumber = (string)e.CommandArgument;
                  CommandEventArgs args = new CommandEventArgs("Control", pageNumber);
                  imageinfo(this, args);
              }
          }

I just need to display an alert message when the event is fired . When i launched the application i don't get any result but if i put the code of the event in the page load i will see the alert.

  • So How can i change my code display the alert in every raise of the event?
4
  • 1
    what client side thingy should cause js to call the server side event? Is it a client side button click, or a text change in a textbox, or a select change in a select box...? Commented May 12, 2014 at 12:21
  • No in my case i have a user control , when i click into a submit button it raises an event which received by the page ( event driven-communication ) So i need in this event to call the js function which change the user control Commented May 12, 2014 at 12:36
  • 1
    What does this user control compose of? It looks to me you are probably handling things in a roundabout manner. You'd have to share that code here to be sure. Commented May 12, 2014 at 12:38
  • 1
    Hi. I suggest you update the observation of our chat in your question post. The issue we've observed is that this is a problem with the PartialUpdatePanel's design. Commented May 14, 2014 at 4:30

4 Answers 4

1

The recommended pattern to solve this problem is a user control. You are correct on this count. However, you've to take care of wiring stuff properly.

You can look at the following article for a guideline: http://www.codeproject.com/Articles/51671/How-To-Expose-Events-from-UserControl

The steps in short are:

  1. You define a delegate
  2. Define an event on that user control using above delegate
  3. Write the necessary plumbing code in the user control code behind
  4. Take care of wiring the code in your aspx markup.

To highlight the 4th point, say its a dropdown inside your user control which contains a list of names. You've defined an event, say NameChanged as follows:

public event NameChangedHandler NameChanged;

In your aspx markup make sure your user control is defined as follows:

<uc1:FooControl runat="server" OnNameChanged="FooCallback"></uc1:FooControl>

Make note of the convention here; in the code behind you've declared event as NameChanged. In your markup, the letters On gets prefixed to it: hence OnNameChanged.

Edit:

Here is an example app; its the same as described above.

MyUserControl.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyUserControl.ascx.cs" Inherits="WebApp.UserControlExample.MyUserControl" %>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem>Jim</asp:ListItem>
    <asp:ListItem>John</asp:ListItem>
    <asp:ListItem>Rosemary</asp:ListItem>
    <asp:ListItem>Catherine</asp:ListItem>
</asp:DropDownList>

MyUserControl.ascx.cs:

using System;

namespace WebApp.UserControlExample
{
    public delegate void NameChangedEventHandler(string name);
    public partial class MyUserControl : System.Web.UI.UserControl
    {
        public event NameChangedEventHandler NameChanged;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (NameChanged != null)
                NameChanged(DropDownList1.SelectedValue);
        }
    }
}

Make note of how the "plumbing" is done. I've put AutoPostback="true" for the dropdownlist; hence I can handle its SelectedIndexChanged event in the code behind of the user control. This is where I can decide on my logic to raise an event.

WebForm1.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.UserControlExample.WebForm1" %>

<%@ Register src="MyUserControl.ascx" tagname="MyUserControl" tagprefix="uc1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
        <uc1:MyUserControl ID="MyUserControl1" runat="server" OnNameChanged="MyUserControl1_NameChanged" />
        <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </form>
</body>
</html>

WebForm1.aspx.cs:

using System;

namespace WebApp.UserControlExample
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void MyUserControl1_NameChanged(string name)
        {
            Label1.Text = "Selected name is <b>" + name + "</b>";
            //you probably want to call your ClientScript.RegisterStartupScript in here...
        }
    }
}

Make note of the event callback on the target aspx webform.

Sign up to request clarification or add additional context in comments.

7 Comments

Sorry @deostroll but i didn't understand what the delegate can add as a plus in my case ( ok it's a good practise), but in my case when i put a breakpoint, i can reach the event instructions but no result ==> I think the problem is that the js method isn't executed
Updated answer with example.
good job :) but my event call back is in the user control ie : the button image is in the user control not in the page
that's why you expose events from user control to aspx page. In your case you'd write all that plumbing code in the image button click. Hope you understand now.
i'm sorry but i still not understand what do u mean by all that plumbing. i put <asp:ImageButton runat="server" AutoPostback="true" ID="edit" ImageUrl="../Design_Ressources/img/thumbs/doc.png" OnCommand="Valider" /> in the user control with this method in code behind protected void Valider (object sender, CommandEventArgs e) { if (imageinfo != null) { imageinfo(); } }
|
0

Script tag should end properly. Check for end script tag...

3 Comments

Please explain your idea :)
The closing script tag is missing in your code. The line csText.Append("script>"); should be csText.Append("</script>"); Also when the page rendered, check the source of the page and see if this script is there ...
Sorry, missed that part. Now please check the generated HTML and see if the script is present...
0

Try using:

cs.RegisterStartupScript

1 Comment

I used it but the same result
0

Try this:

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "error", "alert('Hello');", true);

4 Comments

Could you elaborate more?
@I3arnon its simply a one line code rather than writing long piece of code using string builder. This perfectly generates an alert.
Yes, and i reach this line of code but no alert is appears
@Lamloumi Amazing I am working with the same technique since long :)

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.