Solved

Return Value From Javascript Function to VB.Net.

Posted on 2006-07-24
15
32,367 Views
Last Modified: 2012-05-05
From within my page load event I need to be able to call a javascript function and get the value the function returns.  For example:


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim s As String
        s = "<script>MyFunction();"
        s = s & vbCrLf
        s = s & "</script>"
        Page.RegisterClientScriptBlock("ClientScript", s)
End Sub

**MyFunction Code is in the head section of the aspx document.

How do I get the value that the function MyFunction returns???
0
Comment
Question by:Fraser_Admin
  • 9
  • 4
15 Comments
 
LVL 24

Expert Comment

by:Jeff Certain
ID: 17167293
When I've needed to do something similar in the past, I have used a hidden HTML element to store the result. I then read that result from the view state on postback.

Having said that, in these days of AJAX controls, there may be a far better way.

Also, if you want to execute the function in page_load, couldn't you accomplish the same thing by executing a VB .NET version of the function server-side?
0
 

Author Comment

by:Fraser_Admin
ID: 17167316
Not really because I need to retrieve the value of a page parameter within an embedded frame.  If I use Request.Item("Param1"), then it will only give me the parameters of that frame.  I need a parameter from a parent frame.  I can do this with javascript.  Can you post how to do this with a hidden element?  Not sure how to do that.  I know that you could call a javascript function from within VB.Net, just not sure how to get a return value.
0
 
LVL 18

Expert Comment

by:tusharashah
ID: 17167395
Try following:

1) In your JavaScript function whereever you want to pass value to server side function add this line:
   __doPostBack('CallFunction','123');

2) Now in your PageLoad write following function:
C#
---------
if (Request.Form["__EVENTTARGET"] == "CallFunction")
{
   YourFunction( Request.Form["__EVENTARGUMENT"].ToString() ); // this will pass "123" to the function.
}

VB
---------
Request.Form("__EVENTTARGET")


-tushar
0
 

Author Comment

by:Fraser_Admin
ID: 17167445
OK, let me see if I understand this.

In my page load event I will be calling Myfunction by registering the client script.
Inside the javascript for Myfunction, I will be doing a post back by assigning the value I want to CallFunction.
Then in my page load event, I will check the CallFunction value to get back my value
But can you explain what the YourFunction..... does?
I'm confused at this point.  I think you are on the right track though.

I would like to call the function from the page load
A post back should be ok, I will have to test to see what it is like.
But how do I then get the value back, so I can assign it to a variable that I can use throughout my server side code on that page???
0
 

Author Comment

by:Fraser_Admin
ID: 17167474
Also, on this line of my javascript function, I get obejct expected error

__doPostBack('CallFunction','123');
0
 
LVL 18

Expert Comment

by:tusharashah
ID: 17167615
YourFunction is just an arbitrary function to show how to get value of JS variable in code.

Regarding the object expected error you are getting. Do you have any Postback control on your page? (like button, linkbutton?) If not then you can try adding your custome fucnction like following:

// to call this function: MyPostBack('CallFunction','123');
<script language="javascript" type="text/javascript">
      function MyPostBack(eventTarget, eventArgument) {
            var theform;
            if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
                  theform = document.Form1;
            }
            else {
                  theform = document.forms["Form1"];
            }
            theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
            theform.__EVENTARGUMENT.value = eventArgument;
            theform.submit();
      }

</script>

-tushar
0
 

Author Comment

by:Fraser_Admin
ID: 17167887
__EVENTTARGET is null or is not an object

This is my latest error.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:Fraser_Admin
ID: 17167928
I also get this error on the server side code when trying to print out the value I pass back from the client.

Response.Write(Request.Form("__EVENTARGUMENT").ToString())

System.NullReferenceException: Object reference not set to an instance of an object.
0
 
LVL 18

Expert Comment

by:tusharashah
ID: 17168352
Do you have any button server control one the page? (button-linkbutton?) This process has been straight fwd for me most of the time..

It appears to me like those 2 variable are not getting created in your form automatically. include following two line inside your HTML Form tag:

<input type="hidden" name="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" value="" />

And always check for if EVENTTARGET value exist, before accessing argument.
0
 

Author Comment

by:Fraser_Admin
ID: 17168467
No I do not have any buttons or linkbuttons on this page.  Only a couple of labels.  I tried adding a button, and going back to the __dopostback way, but still got errors.

I tried adding that to the form section of my page.  Still the same error __EVENTTARGET is null or is not an object.
0
 
LVL 18

Accepted Solution

by:
tusharashah earned 500 total points
ID: 17168964
Here's code that I am testing from see if you can find any missing link:
--------------------------------------------------
<HTML>
      <HEAD>
            <title>JS</title>
            <script language="javascript" type="text/javascript">

      function MyPostBack(eventTarget, eventArgument) {
            var theform;
            if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
                  theform = document.Form1;
            }
            else {
                  theform = document.forms["Form1"];
            }
            theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
            theform.__EVENTARGUMENT.value = eventArgument;
            theform.submit();
      }

</script>
      </HEAD>
      <BODY>
            <form id="Form1" method="post" runat="server">
                  <input type="hidden" name="__EVENTTARGET" value="" />
                  <input type="hidden" name="__EVENTARGUMENT" value="" />
                  <input type="button" onclick="MyPostBack('CallFunction','123');" value="Test"/>
                  <asp:Label id="Label1" runat="server">Label</asp:Label>
            </form>
      </BODY>
</HTML>
--------------------------------------------------
private void Page_Load(object sender, System.EventArgs e)
{
      if (Request.Form["__EVENTTARGET"] == "CallFunction")
      {
            Label1.Text = Request.Form["__EVENTARGUMENT"].ToString() ; // this will pass "123" to the function.
      }
}
--------------------------------------------------
0
 

Author Comment

by:Fraser_Admin
ID: 17169145
ok, it works by clicking the button for me.

can this work without having to click a button?
0
 

Author Comment

by:Fraser_Admin
ID: 17169184
'Dim s As String
s = "<script>MyPostBack('CallFunction',querystring('Database'));"
s = s & vbCrLf
s = s & "</script>"
Page.RegisterClientScriptBlock("ClientScript", s)

As soon as I put this code in, it says that __EVENTTARGET is null or not an object

**querystring is my function name that I want to access.
0
 

Author Comment

by:Fraser_Admin
ID: 17191279
Not resolved.  Had to use a workaround.  Will give you the points since u put me in the right direction.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now