Postback from JavaScript

Postback from JavaScript

Calling postback event from Javascript in ASP.NET | ASP.NET Postback with Javascript | Tigger postback from javascript | Postback in asp.net

Hello today we will see how we can trigger a postback in ASP.NET from the clientside using javascript.

We tend to require this many times when we code applications! We will do it using Page.GetPostBackEventReference.

 Simply use the below code.

Javascript Code

function SomeFunction()

{

        if(some condition when you want to trigger postback)

        {

            // trigger postback

            <%= this.Page.GetPostBackEventReference(this,"Delete")%>

        }

        else

        {

            // some other code execution

        }

}

 C# Codebehind Code

    protected void Page_Load(object sender, EventArgs e)

    {

        string eventArg = Request[ "__EVENTARGUMENT" ];

         // if null or empty

         if (!String.IsNullOrEmpty(eventArg))

        {

            switch(eventArg)

            {

                case "Delete":

                     DeleteMethod();

                    break;

                 case "Update":

                     UpdateMethod();

                    break;

                 case "CreateNew":

                     CreateNewMethod();

                    break;

            }

                     

        }

    }

    private void CreateNewMethod()

    {

    }

    private void UpdateMethod()

    {

    }

    private void DeleteMethod()

    {

    }

In the code behind, eachtime a postback takes place it will check on Page Load whether the postback was triggered by javascript code. 
If yes, then based on the eventArg value it will decide which action (method) to trigger.

In the above example the DeleteMethod() will get called as the key passed from javascript is "Delete".

Based on the key you can decide which codebehind method you wish to call and execute.

I tried to stick to the point and make it as simple as possible :) 

Hope it was helpful :)

 

 


Online html editor online JavaScript editorJavaScript For LoopJavaScript Inside Div PanelHTML5 Slider control and JavaScriptJavascript visible hide hyperlinkJquery Dropdown Selected ValueBasics of jqueryLearning JqueryGoogle JQuery CDNHTML5 Canvas AnimationHow to call function in JQuery

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.