Passing JQuery variable to code behind in asp.net

2019-06-10 03:47发布

问题:

I have been trying for a while to get the variable passed from the JQuery function to the code behind so that I can enter it into a database via an SQL statement. However, I never seem to get the variable passed. Or if it is passing, I can't seem to get it to display to make sure it has been passed. Can anyone see what's wrong with my script?

<script type="text/javascript">
  $(function () {
      var comment = $("#comment"),
      allFields = $([]).add(comment);
      $('#<%= hidden.ClientID %>').val(comment);


      $("#dialog-form").dialog({
          autoOpen: false,
          height: 300,
          width: 350,
          modal: true,
          buttons: {
              "Add Comment": function () {
                  var bValid = true;
                  allFields.removeClass("ui-state-error");
                  if (bValid) {
                      $("#comments tbody").append("<tr>" +
                        "<td>" + comment.val() + "</td>" +
                        "<td>" + "<%=currentUser%>" + "</td>" +
                        "</tr>");

                      $(this).dialog("close");
                      //                          
                  }
              },
              Cancel: function () {
                  $(this).dialog("close");
              }
          },
          close: function () {
              allFields.val("").removeClass("ui-state-error");
          }
      });

      $("#NewComment")
    .button()
    .click(function () {
        $("#dialog-form").dialog("open");

    });
  });  
    </script>  

And here is my hidden input field:

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

回答1:

I would suggest to use an actual Asp.Net HiddenField control like this:

Markup:

<div>
    <asp:HiddenField ID="hidden" runat="server" />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</div>

Code Behind:

protected void Button1_Click(object sender, EventArgs e)
{
    string hidden = this.hidden.Value;
    Response.Write(hidden);
}

Javascript:

<script>
    $(document).ready(function () {
        $("#<%=hidden.ClientID %>").val("Hello, World!");
    });
</script>

Output: Hello, World!



回答2:

What are you trying to do with this line: $('#<%= hidden.ClientID %>').val(comment); ? aren't you missing something like comment**.val()**

Still if I were you I would use a simple handler and make a ajax request.