Skip to main content

ICallbackEventHandler - How to invoke a Server side code from client side script without postback in ASP.NET?

Programming with C# SolutionInsights.blogspot.com

I had received above questions from my team mate, hence I thought exploring and writing a post about Call back Event.for our reference.

Now, the actual requirement is a set in the business logic (ASP.NET code) should be executed without page post back from server-side scripting. So, how client callbacks can be achieved within Server-side scripts? Yes, the answer is using ICallbackEventHandler interface with ASP.NET and JQuery scripts. Let’s understand the technique with code snippets, a simple example is taken here for explanation for ease of learning.

1.      Let’s start with Server side code changes, The ICallbackEventHandler interface is inherited to implement the RaiseCallbackEvent and GetCallbackResult methods.
public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{}


=========================================================
Advertisement: Choosing .NET Core Worker Services OR Windows Services?

=========================================================

2.      Create a reference to the CallbackEvent
string callBackRef = Page.ClientScript.GetCallbackEventReference(this, "parameter", "ReturnStatus", "");

Note: 2nd argument "parameter" is parameter name, can be named as anything. 3rd argument "ReturnStatus" is a function name, explained at step 5 below.

3.      Register the Client side script to invoke Server side code
string callBackScript = "function ClientSideMethod(parameter,context)" + "{" + callBackRef + ";}";

Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"",callBackScript,true);

Note: function name ClientSideMethod should be mentioned in client script, on click event.

4.      Next thing, Implement the RaiseCallbackEvent and GetCallbackResult methods
public string GetCallbackResult()
   {
return "Status from Callback method";
//This text is received at client script
   }

   public void RaiseCallbackEvent(string eventArgument)
   {
System.Diagnostics.EventLog.WriteEntry("Application", "Serverside script is executed");
//the expected bussines logic is implemented here, this code snippet writes into eventvwr as simple example.
   }
5.      Finally, Client side changes, Now invoke the Server side code on button click.
<div>
<input type="button" value="Invoke Server Method" onclick="ClientSideMethod('parmeter')"/>
</div>

<script type="text/javascript">
//Client Call back, This method must be implemented.

    function ReturnStatus(result, context)
    {
       alert('Called' + result);
 }

</script>


That’s it. Now you can run the application and click the Invoke button, a new log entry would be created without page postback. For detailed explanation for every step Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages

Happy Learning!

Comments

Anonymous said…
You made it easy.(but advanced scenarios???)
Anonymous said…
well summarized.
Anonymous said…
eаch time i usеd tо read smaller articles or гeνieωs that аlso
clear their motiѵe, and that іs also happenіng with this ρaragraph whiсh I am reаding at this time.
Also see my page > Angry Rants
Anonymous said…
Υou really make it seem so easy with your presеntation but I find
thiѕ topic to be асtually somethіng that
Ι think I would neνer understand. It seеms too complіcatеd and extremely broаd for mе.

I am looking fоrwaгd for уour next роѕt, I ωill try to gеt the hang of it!


Mу webpage :: 02 broadband
Anonymous said…
Greetings from Idaho! I'm bored to death at work so I decided to check out your blog on my iphone during lunch break. I enjoy the info you provide here and can't wait to take a look when I
get home. I'm amazed at how fast your blog loaded on my cell phone .. I'm not even using WIFI, just 3G .

. Anyhow, awesome blog!

Have a look at my web site; Storage Dayton
Anonymous said…
I am regular visitor, how are you everybody? This paragraph posted at this website
is really pleasant.

Have a look at my webpage ... Best online backup providers
Anonymous said…
We're a group of volunteers and starting a new scheme in our community. Your site provided us with valuable info to work on. You've
done an impressive job and our entire community will be thankful to you.


Check out my web-site Best online backup providers
Anonymous said…
There is certainly a lot to find out about this topic.
I really like all of the points you made.

My homepage; Green Coffee bean extract for weight loss
Anonymous said…
There is certainly a lot to find out about this topic.
I really like all of the points you made.

Have a look at my homepage :: Green Coffee bean extract for weight loss
Anonymous said…
Greetings! Quick question that's totally off topic. Do you know how to make your site mobile friendly? My website looks weird when browsing from my iphone. I'm trying
to find a theme or plugin that might be able to correct this problem.
If you have any recommendations, please share. With thanks!



my page :: http://Www.youtube.com/watch?V=ahhfque6Akw
Anonymous said…
Undeniably imagine that which you said. Your favorite justification
seemed to be on the web the easiest thing to be aware of.
I say to you, I certainly get annoyed whilst other folks consider
worries that they plainly don't recognise about. You controlled to hit the nail upon the top and outlined out the entire thing with no need side effect , other people could take a signal. Will likely be again to get more. Thank you

Check out my weblog: Green coffee bean extract for weight loss
Anonymous said…
Hey! I understand this is somewhat off-topic however I
had to ask. Does managing a well-established blog
like yours require a large amount of work? I'm brand new to writing a blog however I do write in my journal on a daily basis. I'd
like to start a blog so I can share my experience
and feelings online. Please let me know if you
have any ideas or tips for brand new aspiring bloggers.
Appreciate it!


http://sites4students.com/index.php?a=stats&u=barryvickers

my blog post; http://corexins.com
Anonymous said…
What's up to every body, it's my first visit of this weblog; this website contains amazing and truly excellent stuff in favor of readers.


Feel free to visit my website: TC-L47E50 Reviews
Anonymous said…
I'd like to find out more? I'd love to find out more details.


my web-site; Acid Reflux remedies
Anonymous said…
Hello there! I simply would like to give you a huge thumbs up for the
excellent info you have got right here on this post.
I will be coming back to your web site for more soon.
Here is my website ; File Sharing Online
Anonymous said…
The only reported side effect procerin xt hair loss treatment of
certain medications. Aloe VeraThis magical plants provides many benefits to
our health, one of them is to improve blood circulation in the
scalp from the tight hairstyle.

Feel free to visit my blog post hair loss in women
Anonymous said…
For example, the American Medical association recommends that every adult take a multivitamin supplement,
and the Food and Drug Administration recognizes that omega three
fatty acids may help prevent heart disease. The problem is that
the primary source of glutamine during exercise is from broken down muscle tissue; the body actually breaks down muscle tissue.


Also visit my webpage ... jacked 3d
Anonymous said…
When choosing the shoes for your hiking trip, it doesn't matter if you have wide or narrow feet, but
make sure that you can find the one that makes you walk in comfort.
I believe that the Hi-Tec Midland hiking boots for men that
Campmor. However, no need to panic if you are an animal rights activist as
most fashion houses used synthetic fur for their collections.


my web page; waterproof hiking boots australia
Anonymous said…
Hello to all, the contents existing at this web page
are in fact awesome for people knowledge, well, keep up the nice work fellows.


Also visit my web page bet angel
Anonymous said…
Communication is key: Because of the risk of pain, partners need to be in communication with each other about
their actions. Don't beat yourself up for not doing
this perfectly. He will not be able to attend their
daughter's high school graduation.

Stop by my blog go to webѕite
Anonymous said…
I havve learn a few good stuff Һere. Certainlу price bookmarking fоr revisiting.
I ԝonder how much attempt you plaсе to make this kind оf ɡreat infcormative website.


Τake a look at my web pаge xtremeantler.org.uk ()
Anonymous said…
It'ѕ awesome in suppօrt of me to havе a web page, which
is hеlpful in favor of my know-ɦow. thanks admin

My website - Tablet PC 2LooK Quad Core CPU the best performance 4GB RAM smartphone android mobitel
Anonymous said…
With havin so much content do you ever run into any issues of plagorism or copyright violation? My site has a lot of unique content I've either
authored myself or outsourced but it seems a lot of
it is popping it up all over the web without my agreement.
Do you know any ways to help stop content from
being ripped off? I'd really appreciate it.

Here is my blog; Christian Louboutin Heels
Anonymous said…
Hey! Dߋ you know if they make any plugins to aѕsist
with Searсh Engine Optimization? I'm trying to
get my blog to rank for some targeted keywords but І'm not seeing
very goоd results. If you know of any pleаse share. Thank you!


Feel free to surf to my weƅ blog: Tablet PC 2LooK Quad Core CPU the best performance 4GB RAM smartphone android mobitel
Anonymous said…
Wow, maгvelous blog layout! Hoѡ long have you been blogging for?
you maҟe blogging look easy. Ƭhe overall look of your site is fantastic, let ɑlone the content!


Here is my web blog; Tablet PC 2LooK Quad Core CPU the best performance 4GB RAM smartphone android mobitel
Anonymous said…
I love reading a post that can make people think.
Also, thank you for allowing me to comment!

Here is my web blog :: magento themes
Anonymous said…
I do agree with all the ideas you have offered in your post.
They're very convincing and can certainly work. Nonetheless, the posts are
very short for novices. Could you please lengthen them a bit
from next time? Thank you for the post.

Also visit my web blog; Christian Louboutin Sale

Popular posts from this blog

Fix: "Cannot set a credential for principal 'sa' . (Microsoft SQL Server, Error: 15535)" and “User is not associated with a trusted sql server connection" Errors

Recently, I had happen to struck with the following errors when I tried to reset the SA password through the SQL Server 2008 R2 Express. " Cannot set a credential for principal 'sa' . (Microsoft SQL Server, Error: 15535) " and then, “ User is not associated with a trusted sql server connection " From my research I have found the solution and that perfectly worked in SQL management studio. Hence, I thought of sharing my findings with others. ========================================================= Advertisement: Choosing .NET Core Worker Services OR Windows Services? ========================================================= Steps to reset the password in SQL Server 2008 R2 Express and fix for the errors: Step 1. Go to SQL Server Instance -> Properties/Security tab and change the mode to SQL Server authentication mode. Step 2. Go to Security/Logins, then open 'sa' login properties,          a. Uncheck the "Enforce passwor...

How to Implement Lombok in IntelliJ for Java Projects: A Step-by-Step Guide

Lombok in IntelliJ for Java Projects Implementing Lombok in your Java project can streamline your code by reducing boilerplate. Follow these steps to set up Lombok in IntelliJ: Step 1 :  Ensure Java SDK Version. Ensure that your project is using Java 8 or higher.  You can check and set the Java SDK version in pom.xml: XML <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> Step 2 : Add Lombok Dependency to pom.xmlOpen the pom.xml file in your project. Add the following Lombok dependency inside the <dependencies> section: XML <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> <scope>provided</scope> </dependency> Step 3 : Download Lombok Plugin for IntelliJ IDEAGo to File > Settings (or press Ctrl+Alt+S). Navigate to Plugins. Search for Lombo...

How to create a GenAI Talking Avatar ChatBot using Streamlit and Anthropic Claude LLM Model

GenAI Talking Avatar ChatBot   using Streamlit and Anthropic Claude LLM Model GenAI-Talking-Avatar-Chatbot is a web application that allows users to interact with an AI-powered talking chatbot with a static avatar. The chatbot uses AWS Bedrock for generating responses and Google Text-to-Speech (gTTS) for voice output. The backend is built with FastAPI, and the frontend uses Streamlit for the user interface. Features API Backend (api.py) Provides an API endpoint to handle chat requests. Uses AWS Bedrock to generate AI responses in a specified JSON format. Ensures the responses include the message, avatar expression, and voice tone. Includes a health check endpoint to verify the API status. Chat UI (chat_frontend.py) Chat Interface: Provides a chat interface where users can input their queries and receive responses from the AI assistant. Avatar Display: Displays an avatar that changes expressions based on the AI assistant's responses and actions (e.g., thinking, speaking). AI Respons...