Call Non-Static Method in Server-Side from Client-Side Using Javsscript

How to call a non-static method from asp.net code behind using jQuery

It is not at all possible because you cannot update any field on UI from server side.

Instead of using WebMethod in aspx page use Asp.Net webservices instead to write web methods which can be called using ajax.

ajax method has a success callback where you can grab the service response and then update the UI field by accessing it with appropriate selector.

E.g

    $(function () {
$("#newBtn").click(function () {
$.ajax({
type: "POST",
url: "AJAXCaller.asmx/GetTimer",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(data){
$("#ClientIdOftime_lbl").text(data);
}

});
return false;
});
});

Call nonstatic method inside static one in web forms

You unfortantly cannot do this.

Remember, once the web page runs the code behind, renders the web page, it is THEN sent down to the client side. On the server, that code, that class, the variables, the web page is tossed in the garbage can. It does NOT exist anymore. The web server is now just sitting there waiting for ANY user - not necessary you to post a whole page back to the server.

So, when you do a ajax call, there is no page post back, and in fact the page class is not re-initialized, and all the web page controls, the code variables, and even the page load events don't exist, don't fire, and can't be used. You have to grasp the concept of a page round trip. Once the page is sent to the client, the server side code, the class, the code variables and EVERYTHING is dumped into the garbage can.

The server does not keep track or keep a instance of each web page. That ONE server takes and will process web pages from ALL of your users - not just YOUR web page.

You might as well of this like calling a stand alone sub routine. After the subroutine exits, the values and code in that subroutine is gone, and goes out of scope.

Same goes for calling static methods. And you can't use any other methods UNLESS you have a page post back. The value of the controls etc. are sitting on your desktop - not the server side. It knows nothing about your web page - you can close the browser, or turn off your computer - the server don't know, and does not care, nor does it have the web page loaded in memory -- it is LONG gone!!

So, some solutions.

Well, pass the values you need from client side.

Say, I have two text box, first name, last name, and I want to do a ajax call to combine first and last, and put the results into a 3rd text box.

I can't touch the web page (sitting on your desktop) controls, so you do it this way - you GET and PASS the information to that web method.

So, say this markup:

    <div>

Enter First Name: <asp:TextBox ID="txtFirst" runat="server" ClientIDMode="Static"></asp:TextBox>
<br />
Enter First Name: <asp:TextBox ID="txtLast" runat="server" ClientIDMode="Static"></asp:TextBox>
<br />
<asp:Button ID="cmdCombine" runat="server" Text="ajax combine" CssClass="btn"
OnClientClick="mycombine();return false;" />

<br />
Full name result:
<asp:TextBox ID="txtFullName" runat="server" ClientIDMode="Static"></asp:TextBox>

<script>

function mycombine() {

MyFirstName = $("#txtFirst").val()
MyLastName = $("#txtLast").val()

$.ajax({
type: "POST",
url: "AjaxTest2.aspx/CombineName",
data: JSON.stringify({ FirstName: MyFirstName, LastName: MyLastName}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (myresult) {
// put result of method call into txtResult
// ajax data is ALWAYS ".d" - its a asp.net thing!!!
$("#txtFullName").val(myresult.d)
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage)
}
});
}
</script>
</div>

and then when we run, we get this:

Sample Image

So, we did get the first name, we did get the last name, and we did shove the results into the full name control.

but, the web method was this:

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

[WebMethod()]
public static string CombineName(string FirstName, string LastName)
{
string MyResult = "";
MyResult = FirstName + " " + LastName;
return MyResult;
}

So, you can get and grab values of controls and pass them to that web method.

The other way? Well, you can drop in a update panel. These so called panels allow you to post back ONLY the bits and parts of the page. So, no full page post-back occures, but in fact what we call a partial page post back. They are perhaps the most amazing feature of web forms.

So, in place of that ajax call, and not wanting a full page re-fresh and post-back?

Drop in the script manager, a update panel, and move all the stuff and controls and button inside of that update panel.

You now dump the JavaScript, dump the web method, and you get this code:

    protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdCombine_Click(object sender, EventArgs e)
{
txtFullName.Text = txtFirst.Text + " " + txtLast.Text;
}

and the markup will now be this:

    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

Enter First Name: <asp:TextBox ID="txtFirst" runat="server" ClientIDMode="Static"></asp:TextBox>
<br />
Enter First Name: <asp:TextBox ID="txtLast" runat="server" ClientIDMode="Static"></asp:TextBox>
<br />
<asp:Button ID="cmdCombine" runat="server" Text="combine first and last" CssClass="btn" OnClick="cmdCombine_Click"
/>

<br />
Full name result:
<asp:TextBox ID="txtFullName" runat="server" ClientIDMode="Static"></asp:TextBox>

</ContentTemplate>
</asp:UpdatePanel>

The page will look the same, but now you did not have to wire up a ajax call, did not have to wire up a web method, and your code behind can freely use the controls INSIDE of the update panel.

You note now that ONLY that part of the page updates, you note that you don't see a full post-back, and in fact you not even see the brwosere "wait/spinner" occur at all.

Do keep in mind that while this is beyond slick and easy?

Your page load event DOES fire each time, but then again, the last 200+ web pages I created ALWAYS but ALWAYS has setup code inside the super beyond improant code stub inside of page load that does this:

if (!IsPostBack) 
{
// my REAL page load code, and my REAL first page setup code
// goes here
}

So consider a update panel - they are pure magic. So, put the controls and stuff you need inside of that panel - including the button click etc. You are free to modify ONLY the controls inside.

Note that regular code and regular full page post backs are not effected, and such code has full use of all controls - including the controls inside of the update panel .



Related Topics



Leave a reply



Submit