How to access JS variable in C#

前端 未结 5 1347
轻奢々
轻奢々 2021-01-15 19:33

Let\'s say I have

500

(Context: asp.net aspx page) How do I allow a c# code access that value?

<
相关标签:
5条回答
  • 2021-01-15 20:01

    Use a hidden input box

    <input id="hiddenControl" type="hidden" runat="server" />   
    

    Put your value in the input box with javascript

    //call this method before you postback, maybe on form submit
    function SetPostbackValues() {
      var hiddenControl = '<%= hiddenControl.ClientID %>';
      document.getElementById(hiddenControl).value = 500; 
      //or some other code to get your value
    }
    

    Access the value with the input box on the server side

    protected void btnSubmit_Click(object sender, EventArgs e) {
       var hiddenValue = hiddenControl.Value;
    }
    
    0 讨论(0)
  • 2021-01-15 20:08

    The C# code inside <% .. %> is run on the server when the HTML is generated. When the value updates via AJAX, it all happens on the client - long after the C# has finished running.

    0 讨论(0)
  • 2021-01-15 20:09

    Ajax, search for it, read about it, find a good library and start implementing

    0 讨论(0)
  • 2021-01-15 20:12

    Server side won't ever have direct access to client's variables (javascript). You have to send them to the server somehow, either via query or post, or through AJAX.

    0 讨论(0)
  • 2021-01-15 20:17

    You can use a server-side div instead, like i.e;

    <asp:Panel ID="blah" runat="server">500</asp:Panel>
    

    Then you can access it and its contents server-side.

    Alternatively;

    <div id="blah"><asp:Literal ID="blahContent" runat="server" Text="500" /></div>
    

    UPDATE: After the question was clarified, it is clear this won't work. The only solution then is to use javascript to get the value, then AJAX to send it to the server.

    0 讨论(0)
提交回复
热议问题