Hi,

I have a problem in my code.
I am putting a image icon in my coe and want to call the code behind function Left_Click() on its OnClick() event.
But the Click event is generating after two times clicking.
and I have wriiten in the Page Load event
I want to write in PageLoad() method

as.Add.Attributes("onclick","javascript:Lef_Click();return false;);

For this I have to write a javascript function Lef_Click() and have to call that code behind function Left_Click() in it.
Is there any method to do this.
Please! Help me out.

Dani AI

Generated

Short answer: client-side JavaScript cannot directly invoke an instance server-side event method (Left_Click). You must either cause a postback so ASP.NET runs the server event or call a server-side WebMethod (AJAX). The “needs two clicks” symptom describes is usually a client-side problem — inspect the generated HTML and the browser console for JavaScript errors (a malformed onclick string or a typo will break the first click).

Two practical approaches:

  • Trigger the server event via postback (reliable for full postback handlers). From code-behind generate the exact postback call so you don’t hand-write the JS; ClientScript.GetPostBackEventReference returns the correct __doPostBack invocation for the control:

    string script = Page.ClientScript.GetPostBackEventReference(myServerControl, "");
    myImage.Attributes["onclick"] = script + "; return false;";

    Or add a hidden server Button wired to Left_Click and call it from JS:

    document.getElementById('<%= btnHidden.ClientID %>').click();
  • Use AJAX for light-weight calls (no full postback): expose a static WebMethod and call it from JS. Give the method the [WebMethod] attribute and call it via PageMethods (or jQuery AJAX):

    [System.Web.Services.WebMethod]
    public static string LeftClickAjax(string arg) { /* ... */ }
    
    PageMethods.LeftClickAjax(someValue, onSuccess, onError);

Passing parameters: with ClientScript.GetPostBackEventReference you can supply an eventArgument string that the server can read (or use a hidden field). With PageMethods you pass typed parameters directly.

Notes and troubleshooting: ’s <%=…%> technique is useful for embedding server values into JS at render time but does not execute server-side code after the page loads. — to send parameters prefer PageMethods or include the value as the eventArgument/hidden field. Always check runat="server" on controls you expect to post back, verify ClientID/UniqueID where needed, and look at the browser console/network log for errors.

u can call a code behind function from JS as


var str = '<%=M1()%>'

where M1() is a server side function . it shuold return some string to JS variable str.

How can i send parameters to the function?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.