jlee
jlee

Reputation: 3175

Access a javascript variable in code behind

So here's what I'm trying to accomplish:

I have a client facing page that loads, and when that happens I automatically run a series of 4 quick tests, if any of those tests fail I update the HCresults variable.

.aspx

  <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script language="javascript" src="script/XmlHttp.js?vers=<%=VersionInfo %>" type="text/javascript"></script>
    <script src="client_scripts/JQuery/jquery-1.9.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        var HCresults = "";
    </script>
  </asp:Content>

I want to access the value of HCresults after the page finishes loading from my code behind page. Is there a way to do this?

Upvotes: 1

Views: 2427

Answers (2)

madasu naga
madasu naga

Reputation: 154

You can write a webmethod in your code behind; pseudo code:

public static var HCresultsCS;
[webmethod]
public static void grabHCresults(var HCresultsfromJS)
{
HCresultsCS= HCresultsfromJS;
} 

make an AJAX post to this webmethod with HCresults you're setting on a test failure as parameter;

Access the HCresultsCS from CS now. Check for nulls! I can't comment This link might be helpful: http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

Upvotes: 1

Trasiva
Trasiva

Reputation: 494

Unfortunately not using JS, you can store the value in a hiddenfield however to retrieve in C#. Make sure that you set the attribute runat = "server" for the control. I should also mention you'll use element.value = value to assign the value.

Upvotes: 0

Related Questions