Return Value From Javascript Function to VB.Net.

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???
Fraser_AdminAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jeff CertainCommented:
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
Fraser_AdminAuthor Commented:
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
tusharashahCommented:
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
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

Fraser_AdminAuthor Commented:
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
Fraser_AdminAuthor Commented:
Also, on this line of my javascript function, I get obejct expected error

__doPostBack('CallFunction','123');
0
tusharashahCommented:
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
Fraser_AdminAuthor Commented:
__EVENTTARGET is null or is not an object

This is my latest error.
0
Fraser_AdminAuthor Commented:
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
tusharashahCommented:
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
Fraser_AdminAuthor Commented:
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
tusharashahCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Fraser_AdminAuthor Commented:
ok, it works by clicking the button for me.

can this work without having to click a button?
0
Fraser_AdminAuthor Commented:
'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
Fraser_AdminAuthor Commented:
Not resolved.  Had to use a workaround.  Will give you the points since u put me in the right direction.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.