Solved

Return Value From Javascript Function to VB.Net.

Posted on 2006-07-24
15
32,486 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

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
 

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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
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…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

627 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