Search code examples
c#javascriptasp.nethiddenfield

javascript ASP.NET hiddenfield get value from code behind


I am trying to integrate my codes to Google Chart API. I want to manually set google chart title and axis column names from code behind. I tried below code but doesn't work. Any suggestions?

ASPX file

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", { "packages": ["corechart"] });
        function drawProgrammingChart() {
            var data = new google.visualization.DataTable(operationdetails, 0.5);
            var chart = new google.visualization.LineChart(document.getElementById("divprog"));
            **var xAxis = document.getElementById("txtXAxisName");**
            **console.log(xAxis);**
            var yAxis = document.getElementById("txtYAxisName");
            chart.draw(data, {
                title: "Visualization Satisfaction", hAxis: { title: "Programming method" }, vAxis: { title: "Units" }
            });
        }
        google.setOnLoadCallback(drawProgrammingChart);
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div id="divprog" style="width: 750px; height: 350px;">
        </div>
    <asp:HiddenField ID="txtXAxisName" runat="server" />
    <asp:HiddenField ID="txtYAxisName" runat="server" />
</asp:Content>

In code behind i want manually to set hidden field value.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = generateDataTable();
                **txtXAxisName.Value = "Days";**
                txtYAxisName.Value = "Duration";
                LoadChart(dt, "operationdetails");    
            }

        }
private void LoadChart(DataTable table, string jsName)
        {
            Page.ClientScript.RegisterStartupScript(
                this.GetType(),
                jsName, string.Format("var {0} = {1};", jsName, new Bortosky.Google.Visualization.GoogleDataTable(table).GetJson()), true);
        }

When getting element txtAxisName, it gets null.


Solution

  • As Cal279 indicated, i view the source code of the page rendered and see below:

    <input type="hidden" name="ctl00$MainContent$txtXAxisName" id="MainContent_txtXAxisName" value="Days" />
    

    Then i tried below and it worked. Thanks to Cal279 :)

    var xAxis = document.getElementById("MainContent_txtXAxisName");