Question

Is it possible to to programmatically trigger a postback from server code in ASP.NET? I know that it is possible to do a Response.Redirect or Server.Transfer to redirect to a page, but is there a way to trigger a postback to the same page in server code (i.e. without using javascript trickery to submit a form)?

Was it helpful?

Solution

Asp.net Postbacks are initiated from the client (typically form submission). I am not sure what you are trying to achieve. Some of the server side page lifecyle events are already executed and what you are trying to do is raise the previous event handlers again.

OTHER TIPS

Postbacks are caused by a FORM submission. You need to initiate them from the client.

You could do it with an Ajax request. You'd have to have the page polling the server. There isn't any way for the server to push information out to the browser without requesting it. But having some Javascript that runs in the background and polls the server every 5 seconds (or more, depending on your needs) would probably be the best solution.

APPEND

If you go this route, you can have the server send back just a yes or no, or even just 0 or 1 depending on whether or not the postback should be performed. Depending on your needs, there many be no reason to actually use the XML part of AJAX. Just run a simple Asynchronous request, possibly with a few querystring variables, and get back a simple one word, or even a number as a response. That way you can keep the javascript for creating and parsing the XML out if it isn't needed.

If you are looking to initiate communication from the server, rather then polling, have a look at Microsoft's SignalR. The easiest context for this, and one the SignalR has as part of its example code is a chat application. You will be able to initiate messages from code behind and receive them as javascript events on your page.

Server Code To Send:

using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the broadcastMessage method to update clients.
            Clients.All.broadcastMessage(name, message);
        }
    }
}

Client Code to catch server messages is the override of 'chat.client.broadcastMessage':

<script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub. 
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (name, message) {
                // Html encode display name and message. 
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page. 
                $('#discussion').append('<li><strong>' + encodedName
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.  
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub. 
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
            });
        });
    </script>

For those using newer versions of .NET, you have to use Page.ClientScript.GetPostBackEventReference since 'this.GetPostBackEventReference(...)' is obsolete. Also probably Page.ClientScript.RegisterStartupScript(...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top