Farhan
Farhan

Reputation: 2575

Calling code behind method from Client

Apparently it is a very simple problem. I have a button on an ASPX page:

<input id="ok" type="button" name="ok" value="OK">

When this button is clicked, I want to call a method in code behind and do a postback afterwords.

What I have found so far is using __doPostback etc. but also came to know that Microsoft is moving away from it. Maybe ClientScriptManager.GetPostBackEventReference can work too but I am not sure how it can be done.

I cannot use an AJAX call from jQuery because of some restrictions.

Upvotes: 0

Views: 1819

Answers (4)

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

If you are able to generate asp:button then it will be easy for you . You can add event handler to you button generated dynamically. ie)

btnClick.OnClick += new EventHandler(btnClick_Click);


Protected void btnClick_Click(object sender, EventArgs e)
{
    // code goes here
}

Upvotes: 1

Jha.prashant
Jha.prashant

Reputation: 263

You can use in you aspx markup:

<input id="ok" runat="server" onserverclick="btnOk_ServerClick" type="button" name="ok" value="OK">

and put this code in aspx code behind(.cs) file:

 protected void btnOk_ServerClick(object sender, EventArgs e)
        {
}

Upvotes: 2

Pantelis Natsiavas
Pantelis Natsiavas

Reputation: 5369

You could alternatively call an http handler. You could also implement a web service of some kind, either REST or SOAP.

Each of the above could be called using a javascript event (for example onclick) registered on the specific html button, out of ASP.NET page lifecycle. For example you could call this function on the onclick event (targetURL would be replaced by the URL of http handler, or the respective service):

<button onclick="httpGetRequest('targetURL')">Click me</button>

function httpGetRequest(theUrl)
{
    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

Hope I helped!

Upvotes: 1

Pouya Samie
Pouya Samie

Reputation: 3723

Just put runat="server" tag on this input then you can access it on code behind

Update: if you wanna call a method look at this samples. this and this

Upvotes: 1

Related Questions