Click here to Skip to main content
15,886,732 members
Articles / Web Development / ASP.NET
Alternative
Article

How to post back to the server using JavaScript in ASP.NET

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
29 May 2012CPOL1 min read 41.4K   367   14   5
This is an alternative for "How to post back to the server using JavaScript in ASP.NET"

Introduction

The code in the original article works great and causes postback from JavaScript. However, it doesn't let you pass a variable argument back from JavaScript. I made some slight modifications to the code to allow it to pass a single string variable from JavaScript to codebehind.

Background

Basically, as Scott Norberg noted in his original article, http://www.codeproject.com/Articles/42183/How-to-post-back-to-the-server-using-JavaScript-in, were trying to avoid using __doPostback to cause a postback from javascript in .Net, and instead use documented .Net framework class "PostBackOptions" to cause the postback. This extension to his code allows for passing a variable from JavaScript also.

Using the code

Here are my changes (my code is in VB). First step is to write a small EventArg class:

C++
Public Class JavaScriptPostbackEventArgs
    Inherits EventArgs

    Public args As String = ""

    Public Sub New(args As String)
        Me.args = args
    End Sub
End Class

Next, change the postback event's type to use this new class:

C++
Public Event Postback As EventHandler(Of JavaScriptPostbackEventArgs)

Now the next task is to get the JavaScript to pass a single string variable. This is done by changing the Render method:

The first step is to add an argument to the option:

C++
options.Argument = "arg"

Next, also add it as a variable in the javascript function call:

C++
writer.Write([String].Format("{0} = function(arg) {1}", functionName__1, "{"))

When GetPostBackEventReference renders this, it renders arg is a string value, not a variable. The following will remove the single quotes off of arg and use the variable:

writer.Write(Me.Page.ClientScript.GetPostBackEventReference(options).Replace("'arg'", "arg"))
Here is the full Render method:
VB
Protected Overrides Sub Render(writer As HtmlTextWriter)
    MyBase.Render(writer)
    Dim options As New PostBackOptions(PostbackButton)
    options.PerformValidation = Me.CausesValidation
    options.ValidationGroup = Me.ValidationGroup
    options.Argument = "arg"

    Dim functionName__1 As [String] = If(JavaScriptNamespaces.Equals([String].Empty), FunctionName, [String].Concat(JavaScriptNamespaces, ".", FunctionName))
    Dim arg As String = "e"
    writer.Write("<script type='text/javascript'>")
    AddNamespaces(JavaScriptNamespaces, writer)
    writer.Write([String].Format("{0} = function(arg) {1}", functionName__1, "{"))
    writer.Write(Me.Page.ClientScript.GetPostBackEventReference(options).Replace("'arg'", "arg"))
    writer.Write("};")
    writer.Write("</script>")
    Me.Page.ClientScript.RegisterForEventValidation(options)
End Sub
Now finally the raise postback event will get the EventArgument from the request:
VB
Private Sub PostbackButton_Click(sender As Object, e As EventArgs)
    RaiseEvent Postback(sender, New JavaScriptPostbackEventArgs(HttpContext.Current.Request("__EVENTARGUMENT")))
End Sub

That's all the changes.

Example of how to use

Here is an example on how to use it from the client side. Add the control the page markup:

VB
<uc:JavascriptPostBack runat="Server" ID="ucPostback" FunctionName="javaPostback" />

A simple javascript example to call the function is: You can use this inside another function.

VB
<script>
javaPostback('test');
</script>

And finally the code behind that handles the event:

VB
Private Sub ucJavascriptpostback_Postback(sender As Object, e As JavaScriptPostbackEventArgs) Handles ucNodeClickPostback.Postback    


End Sub

In the above example, e.args will have the value 'test'.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
My area of expertise is developing management database systems for business so that they can efficiently store and lookup existing customer's information and related data, and be able to generate various reports. My goal is to always deliver innovative design and a user friendly interface.

Comments and Discussions

 
QuestionHow to implement the post back from a pop up page to master Pin
abiFarrah13-Jan-13 13:57
abiFarrah13-Jan-13 13:57 
SuggestionOh, 'bout your picture, Razi ... Pin
MacSpudster1-Jun-12 6:49
professionalMacSpudster1-Jun-12 6:49 
GeneralDitch that method, use jQuery's .ajax calll Pin
MacSpudster31-May-12 12:52
professionalMacSpudster31-May-12 12:52 
GeneralRe: Ditch that method, use jQuery's .ajax calll Pin
Razi Syed31-May-12 14:05
Razi Syed31-May-12 14:05 
GeneralRe: Ditch that method, use jQuery's .ajax calll Pin
HaBiX31-May-12 21:14
HaBiX31-May-12 21:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.