Click here to Skip to main content
15,885,104 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I tried hidden field control but it doesn't return java script value to find code behind in c#. When I execute below code, it returns value always 0.
How to get distance value from java script to c#?
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
    function GetDistance()
    {
        var origin = document.getElementById("orig").value,
            destination = document.getElementById("dest").value,
            service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
            {
                origins: [origin],
                destinations: [destination],
                travelMode: google.maps.TravelMode.DRIVING,
                avoidHighways: false,
                avoidTolls: false
            },
            callback
        );

        function callback(response, status) {
                var orig = document.getElementById("orig"),
                dest = document.getElementById("dest"),
                dist = document.getElementById("dist");
            if (status == "OK") {
                orig.value = response.originAddresses[0];
                dest.value = response.destinationAddresses[0];
                dist.value = response.rows[0].elements[0].distance.text;
                document.getElementById('<%=hdnResultValue.ClientID%>').value = dist.value;
                
            } else {
                alert("Error: " + status);
            }
        }
    }
</script>


<form id="frm1"  runat="server" method="post">
    <br>
    Basic example for using the Distance Matrix.<br><br>
    Origin: <input id="orig" type="text" style="width:35em"><br><br>
    Destination: <input id="dest" type="text" style="width:35em"><br><br>
    Distance: <input id="dist" type="text" style="width:35em">
    <asp:Button ID="btnSubmit" runat="server" Text ="Submit Application" OnClientClick="GetDistance();" OnClick="btnSubmit_Click" />
    <asp:Label ID="lblDistance" runat="server" Text=" " />
    <asp:HiddenField ID="hdnResultValue" Value="0" runat="server" />
    </form>


code behind c#
XML
protected void btnSubmit_Click(object sender, EventArgs e)
        {
            lblDistance.Text = hdnResultValue.Value;
            lblDistance.Text += "Calculated Successfully";
        }
Posted
Updated 24-Jun-15 4:56am
v4
Comments
Sergey Alexandrovich Kryukov 24-Jun-15 10:37am    
Not clear. What do you want to achieve, exactly? C# never gets any "JavaScript value", because JavaScript works on the client side, and C# on server side.
—SA
F-ES Sitecore 24-Jun-15 10:49am    
do you see your "hello2" alert? Is Status "OK"? If you put an alert after you set the hidden variable does it contain what you expect?

document.getElementById('<%=hdnResultValue.ClientID%>').value = dist.value;
alert(document.getElementById('<%=hdnResultValue.ClientID%>').value);

Do you get any error in the console?
Member 9018012 24-Jun-15 11:01am    
I need to get distance value in c#. then I have to implement this into the application for crud process further?
So My question is how to get java script distance value into c#?
F-ES Sitecore 24-Jun-15 11:32am    
You have simply restated your question. We can't access your system and know your inputs etc, so we can't debug through your code. If you learned to debug your code rather than expecting us to somehow do it remotely then you'll quickly find out what the issue is. I asked some questions that were designed to narrow down where the problem might be but you didn't answer any of them. Giving people a wall of code and expecting them to know what is going wrong is not very reasonable.

The problem is that you're submitting the form before the AJAX call completes. You need to delay the form submission until the callback function has been called.

Something like this might work:
C#
var submitFromCode = false;

function GetDistance(){
    // If the button was triggered by the "callback" function, submit the form:
    if (submitFromCode) { return true; }

    var origin = document.getElementById("orig").value,
        destination = document.getElementById("dest").value,
        service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
        {
            origins: [origin],
            destinations: [destination],
            travelMode: google.maps.TravelMode.DRIVING,
            avoidHighways: false,
            avoidTolls: false
        },
        function(response, status) {
            var orig = document.getElementById("orig"),
                dest = document.getElementById("dest"),
                dist = document.getElementById("dist");

            if (status == "OK") {
                orig.value = response.originAddresses[0];
                dest.value = response.destinationAddresses[0];
                dist.value = response.rows[0].elements[0].distance.text;
                document.getElementById('<%=hdnResultValue.ClientID%>').value = dist.value;

                // Submit the form:
                submitFromCode = true;
                document.getElementById('<%=btnSubmit.ClientID%>').click();

            } else {
                alert("Error: " + status);
            }
        });

    // Prevent the form from being submitted until the "callback" function is called:
    return false;
}
 
Share this answer
 
try accessing it from the form directly:


HTML
<input type="hidden" id="hdnResultValue" name="hdnResultValue" value="" />

C#
String test = Request.Form["hdnResultValue"];



UPDATE: Tested Version:

Page1.aspx:
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" >

        function btnClick() {
            document.getElementById("hdnHidden").value = "test";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <input type="hidden" id="hdnHidden" name="myHidden" />
        <button type="button" id="btnButton" name="myButton" onclick="btnClick();" >btnClick</button>
        <button type="submit">submit</button>
    </form>
</body>
</html>


Page1.aspx.cs:
C#
using System;
namespace WebTests
{
    public partial class Page1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            string test = Request.Form["myHidden"];
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            string test = Request.Form["myHidden"];
        }
    }
}


The page has two buttons. "btnClick" runs the javascript that changes the hidden fields value. "submit" submits the form containing the hidden field.
In both page load methods the value of "string test" is "test"

Take a look at mu code, compare it to yours and try to see whats different, i.e. is hdnResultValue within the form being submitted?
 
Share this answer
 
v3
Comments
Member 9018012 24-Jun-15 11:02am    
It doesn't work.
Andy Lanng 24-Jun-15 11:09am    
oh yeah - my mistake - I think it needs to be the unique id :S

Just use a plain hidden input type - Check my updated solution
Member 9018012 24-Jun-15 11:24am    
returns null
Andy Lanng 24-Jun-15 11:28am    
where are you putting the code? In an event?
Member 9018012 24-Jun-15 11:34am    
I used plain hiddenfield in .aspx file

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900