skip to Main Content

I have a div object (riddleIdHere), and js code that during the running inserts a number into this div. I want my C# code-behind to use this number, but the code-behind gives me an empty string like I have never inserted a number into this div.
Can anyone help me, please?

Here’s my div:

<div id='riddleIdHere' runat='server' style='display:none'></div>

Js:

document.getElementById("riddleIdHere").innerText = riddleid;

*riddleid is a numeric variable

my code-behind is supposed to update a data table using my InnerText:

sql = "UPDATE YHRiddles " +
    "SET rateSum +='"+ b + "' " +
    "WHERE id = '" + riddleIdHere.InnerText + "';";
Debug.WriteLine(riddleIdHere.InnerText);

The Debug.WriteLine is here to see why it doesn’t work, and it prints an empty string.

2

Answers


  1. What you change on page using javascript its not automatically send on code behind.

    To do that you have to create an other hidden input control (that is the actually one that can send post back insformations on code behind) and also write there what information’s you need to send on value not anywhere else. The Value is the only one that you can send.

    The InnerText on code behind is to give some information on how to render your control – did not have interactivity with the final page.

    Example : Page.aspx

    <head runat="server">
        <title></title>
    
            <script>
            function OpenIt()
            {
                document.getElementById("<%=riddleIdHere.ClientID%>").innerText = "some text";
                document.getElementById("<%=hfRiddleStatus.ClientID%>").value = "some text";
                form.s
            }
            </script>
    
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <div id="riddleIdHere" runat="server" >Some Content</div>
                
    
                <asp:HiddenField runat="server" id="hfRiddleStatus" Value="0" />
    
                
                <asp:Button runat="server" Id="btnRunMe" OnClick="btnRunMe_Click" OnClientClick="OpenIt();" Text="RunMe" />
    
                <asp:Literal runat="server" ID="txtDebugInfos" EnableViewState="false"></asp:Literal>
            </div>
        </form>
    </body>
    </html>
    

    Code behind:

    protected void btnRunMe_Click(object sender, EventArgs e)
    {
        txtDebugInfos.Text = hfRiddleStatus.Value;
    }
    

    What to expect – after the click the hfRiddleStatus.Value must contains the "some text" we put using javascript.

    Login or Signup to reply.
  2. You can create a Literal:

    <asp:Literal runat="server" ID="riddleIdHere" Text="" Visible="false"></asp:Literal>
    

    and then set asp literal text with js.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search