Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to get javascript values on code behind in c#.I know i can use hidden field but there is no server control on page for postback.Please tell me how can get vales in code behind.

Here is my code:

<html>
<head>
<title>Facebook Get Logged in User Details UserName,Email,Profile Image</title>
    <script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
    // Load the SDK Asynchronously



    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    } (document));

    // Init the SDK upon load
    window.fbAsyncInit = function () {
        FB.init({
            appId: 'APPID', // App ID
            channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });

        // listen for and handle auth.statusChange events
        FB.Event.subscribe('auth.statusChange', function (response) {
            if (response.authResponse) {
                // user has auth'd your app and is logged into Facebook
                var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
                FB.api('/me', function (me) {
                    document.getElementById('auth-displayname').innerHTML = me.name;
                    document.getElementById('myJSString').value = me.name;

                    alert(document.getElementById('myJSString').value);

                    document.getElementById('Email').innerHTML = me.email;
                    document.getElementById('profileImg').src = uid;

                    //  document.getElementById('ctl00_CPHDefault_tcTPS_TPProd_ctl01_tcProduction_TPNewT‌​itlesStatus_ChangedRowsIndicesHiddenField').value = uid;
                   // alert('yyy');

                })
                document.getElementById('auth-loggedout').style.display = 'none';
                document.getElementById('auth-loggedin').style.display = 'block';
            } else {
                // user has not auth'd your app, or is not logged into Facebook
                document.getElementById('auth-loggedout').style.display = 'block';
                document.getElementById('auth-loggedin').style.display = 'none';
            }
        });
        $("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
    }





</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div id="Result"  class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login</div>
</div>
<div id="auth-loggedin" style="display: none">
Name: <b><span id="auth-displayname"></span></b>(<a href="#" id="auth-logoutlink">logout</a>)<br />
Email: <b><span id="Email"></span></b><br />
Profile Image: <img id="profileImg" />

<form runat="server">
<asp:HiddenField runat="server" id="myJSString" />

</form>
</div>
</div>
</body>
</html>

You can see there is no server control so how i can get NAME,UID variables in code behind.

Thanks

share|improve this question
1  
See stackoverflow.com/questions/5463266/… –  emd Jul 17 at 12:58
add comment

3 Answers

up vote 1 down vote accepted

I would investigate the use of ASP.NET AJAX Page Methods, because they allow for script callable stand-alone web services that live in an .aspx page, like this:

Page Method in your code-behind file (call it default.aspx for discussion's sake):

[WebMethod]
public static string SaveData(string name, string uid)
{
    // Logic here to do what you want with name and uid values (i.e. save to database, call another service, etc.)
}

jQuery call to default.aspx's SaveData method:

$.ajax({
    type: "POST",
    url: "default.aspx/SaveData",
    data: "{'name':'John', 'uid':'ABC123'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        // Do something interesting here.
    }
});

Notes: ASP.NET AJAX Page Methods automatically encode their response to JSON so you will not see any JSON serialization in the code-behind or any serialization logic at all.

For more information about ASP.NET AJAX Page Methods check out Using jQuery to directly call ASP.NET AJAX page methods

share|improve this answer
 
@KAarl i have edit and post my full code now tell me how i can use ajax posting in existing code ..Thanks –  sikha Jul 17 at 13:54
 
What client-side event do you want to trigger the passing of name and UID values to the C# code-behind on the server? –  Karl Anderson Jul 17 at 14:00
 
@anyone you suggest? –  sikha Jul 17 at 14:11
 
well it depends upon what you are doing with the name and UID on the server, I think you need to explain more clearly what you are trying to accomplish with this data in the code-behind. –  Karl Anderson Jul 17 at 14:13
 
i have to save facebook user information in database fields.Right now i am getting information in javascript.you can check. –  sikha Jul 17 at 14:15
show 4 more comments

You can use a hiddenfield server control assign the values you need to it in javascript and assess it on server side. If you do not want post back then you can use jQuery ajax to send values.

Html

<asp:hiddenfield id="ValueHiddenField" runat="server"/>

Javascript

document.getElementById('ValueHiddenField').value = "yourValue";

Code behind

string yourValue = ValueHiddenField.Value;

Using jQuery ajax and web method to send values to code behind, you can find nice tutorial over here.

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: {'yourParam': '123'},
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});

Code behind

[WebMethod]
public static void YourMethod(string yourParam)
{
   //your code goes here
}
share|improve this answer
 
And what mechanism gets you to the code-behind? –  Karl Anderson Jul 17 at 13:03
 
You need to do post back, or you can use jQuery ajax call to send values. –  Adil Jul 17 at 13:04
 
+1 nice answer.. –  Habib Jul 17 at 13:05
 
I think the OP is trying to avoid doing a postback, because otherwise I think they would have added a server control to the page, but I may be wrong. –  Karl Anderson Jul 17 at 13:06
1  
Check my updated answer. –  Adil Jul 17 at 13:14
show 5 more comments

You can use following method:

<script language="javascript" type="text/javascript">
    function returnString() {
        var val = 'sampleValue';
        return val;
    }
</script>

C# Code to get the return value of the above function:

ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", "<script language="javascript">var a=returnString();alert(a);</script>");

Or simply as Adil said, can use hidden field and assign value:

<asp:HiddenField ID="hField" Value="0" runat="server" />
        <asp:Button ID="Button1" runat="server"  OnClientClick="returnString();"
            Text="Button" onclick="Button1_Click" />

script for assigning value:

<script language="javascript" type="text/javascript">
       function returnString() {
           debugger;
           document.getElementById("hField").value = "sampleValue";
       }
   </script>
share|improve this answer
 
I cannot use any server side control like button etc.. –  sikha Jul 17 at 13:07
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.