How to pass a variable from JavaScript to ASP

Forrest :

I'm not really sure what I'm doing wrong. I would like to pass a variable from a JS function to ASP, and then print it in the console at a button click.

JS function:

<script>
    function can() {
        var candy = "Chocolate";
        document.getElementById("Hidden1").value = candy;
    }
</script>

ASP.net:

<form id="form1" runat="server">

    <div>
        <input id="Hidden1" type="hidden" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClientClick="can()"  Text="Button"
            onclick="Button1_Click" />
    </div>
</form>

<script runat="server">
    protected void Button1_Click(object sender, EventArgs e){

        Response.Write(Hidden1.Value);
    }

</script>
Md Farid Uddin Kiron :

You have placed your aspx.cs file in wrong place which should be in .cs file. You should try like below:

Aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebFormTest.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

    <form id="form1" runat="server">  

     <div>
        <input id="Hidden1" type="hidden" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClientClick="can()"  Text="Button"
            onclick="Button1_Click" />
    </div>
    </form>

     <script>
        function can() {
        var candy = "Chocolate";
        document.getElementById("Hidden1").value = candy;
    }
</script>

</body>
</html>

Aspx.cs:

 protected void Button1_Click(object sender, EventArgs e)
        {

            Response.Write(Hidden1.Value);
        }

Test Result:

enter image description here

How To Get It Worked:

As per your comment: You have WebForm1.aspx page If you expand it you would get WebForm1.aspx.cs file just paste your cs file there will be work as expected.

See the screenshot for more clarity:

enter image description here

I have tested and working as expected.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29895&siteId=1