简体   繁体   中英

Calling server-side C# function from either javascript or codebehind c# function ASP.NET

I want to call a function in an API that lives in a foreign server and get the result of this function. I want to do all this through a button click on an ASP.NET page on the client side. For simplicity, let's say this function takes in some parameter, appends a string to it and returns it. I want to render this returned string on the webpage. Lets say this is the server-side function:

public string Appender(string x)
{
     return x + "1";
}

Now, lets say I have a button on my asp.net webpage:

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" />

And a label:

<asp:Label ID="Label1" runat="server"></asp:Label>

My question is, what would go inside the Button1_Click function to call Appender (which is on the server-side)?

protected void Button1_Click(object sender, EventArgs e)
{ 
 //TODO, call Appender, get result, set Label1's text to the returned string.
}

Or, should I be using javascript within the asp.net page to do this? I haven't messed around with javascript/ajax much so if that's the way to go, some guidance in that would be helpful also. Thanks.

what would go inside the Button1_Click function to call Appender

Call to the appender method will go here. Say the name of class that has this method is ClassA. The you will create an instance of ClassA and call the method. Like

ClassA obj = new ClassA();
obj.Appender("yourstring");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM