Reading SQL Server results from asp.net into JavaScript

Rate It (1)

Last post 10-04-2006 3:40 PM by golfvilla. 9 replies.

Sort Posts:

  • Reading SQL Server results from asp.net into JavaScript

    09-14-2006, 1:43 PM
    • Loading...
    • golfvilla
    • Joined on 08-10-2005, 11:57 AM
    • Rockledge, FL
    • Posts 10
    I have searched the world over for a simple way to read Latitude and Longitude settings from my SQL Server database, from ASP.NET into JavaScript so I can set point markers in my google map based on the data in the database. Can someone provide a link or links that will show how I can do this? Thanks in advance!
  • Re: Reading SQL Server results from asp.net into JavaScript

    09-15-2006, 2:40 AM
    • Loading...
    • mokeefe
    • Joined on 08-20-2006, 5:15 AM
    • Canberra Australia
    • Posts 2,096

    Create an ASPX Page that streams the corresponding javascript back to the client.

    Eg. See if you understand mmy post here - it has my usual typo's. If you do not understand post more data, including the parameters for retrieving the page info, and the values that must be returned in Javascript and I will assist.

    http://forums.asp.net/thread/1398942.aspx

    Rgds,

    Martin.

     

     

    Rgds,
    Martin.

    For the benefit of all users please mark any post answers as appropriate.
  • Re: Reading SQL Server results from asp.net into JavaScript

    09-15-2006, 9:03 AM
    • Loading...
    • golfvilla
    • Joined on 08-10-2005, 11:57 AM
    • Rockledge, FL
    • Posts 10

    Thanks for your help Martin!!!

    Here is a rather length snippet of code that should explain what I am trying to do. As you can probably tell, what I am currently doing is providing an ASPX page with a map of Florida. Each of the 8 regions of  the map have a polygon area that the user clicks on. When the user clicks on a specific region, a JavaScript function for that specific region, i.e. SE() for the South East region, is called. The JavaScript function reads the information from an XML file for that region (SE_Data.xml). This all works fine. What I need to do is read the current information from a SQL Server database that has data (including Latitude and Longitude) for hotels in the selelected area. I could have the ASP.NET code read the latest data from the database and create an XML file for each region. Considering there are 8 regions, this would take too long. I need to come up with away to read the database after the region is selected by the user. Here is the C# code:

    <%@ Page Language="c#" EnableViewState="True" %>
    <%@ import Namespace="System.Data" %>
    <%@ import Namespace="System.Data.SqlClient" %>
    <%@ import Namespace="System.Web.Security " %>
    <%@ import Namespace="System.IO" %>
    <%@ import Namespace="System.Collections" %>
    <%@ import Namespace="System.web.UI.WebControls" %>
    <%@ import Namespace="System.Drawing" %>

    <script runat=server>
      .
      .
      .


          // ASP.NET code to create XML files from Region.dbo SQL Server Database


       .
       .
       .
    </script>


    <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
    </script>

    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=[my google map key]"
          type="text/javascript"></script>
      
      
    <script type="text/javascript">
        //<![CDATA[

     

       // Load State of Florida Map with message callout

        function load() {
          if (GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("map"));
      map.addControl(new GSmallMapControl());
            map.addControl(new GMapTypeControl()); 
            map.setCenter(new GLatLng(28.4565, -81.4676), 6);
      var textMessage = "Coming Soon: Official Meetings Maps!";

            map.openInfoWindow(map.getCenter(), document.createTextNode(textMessage));
          }
        }

       // Create Google Map point references and markers for each of the 8 regions in the state.
      .
      .
      .
      .
      .
      .
      .

         function SE() {
          this.map = new GMap2(document.getElementById("map"));
          this.map.addControl(new GSmallMapControl());
          this.map.addControl(new GMapTypeControl());
          this.map.setCenter(new GLatLng(26, -80.5), 8);


         // Creates a marker at the given point with the given number label
          function createMarker(point, tag) {
            var marker = new GMarker(point);
            GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(tag);
            });
           return marker;
           }


         // Get the xml file for this region
          GDownloadUrl("SE_Data.xml", function(data, responseCode) {
            var xml = GXml.parse(data);
            var markers = xml.documentElement.getElementsByTagName("marker");
       for (var i = 0; i < markers.length; i++) {
              var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                      parseFloat(markers[i].getAttribute("lng")));
             
              var tag = (("<p align='left'><font face='verdanda'><strong>") + markers[i].getAttribute("company") + ("</strong></font><br />") +
                   markers[i].getAttribute("ADDR1") + ("<br />") +
                   markers[i].getAttribute("CITY") + (", ") +
                   markers[i].getAttribute("ST") + ("   ") +
                   markers[i].getAttribute("ZIP") + ("<br />PH: ") +
                   markers[i].getAttribute("PHONE") + ("<br />Website: <a href='http://") +
                   markers[i].getAttribute("WEBSITE") + ("' target='_blank'>") +
                   markers[i].getAttribute("WEBSITE") + ("</a></p>"));
       
              map.addOverlay(createMarker(point, tag));
            }
          });
        }

        //]]>
        </script>

    </head>
    <body>
    <form action ="search.aspx" runat="server">
    <table>
      <tr>
        <td>
          <img src="images/flamap1.gif" width="350" height="306" border="0" usemap="#MAP2">
            <map name="MAP2">
              <area shape="poly" coords="118,18,118,18,135,65,108,76,23,44,20,14" href="javascript:NW()">
              <area shape="poly" coords="123,30,214,37,222,82,210,82,203,102,188,99,134,62" href="javascript:NC()">
              <area shape="poly" coords="248,29,245,44,260,89,240,90,227,85,222,76,216,40,220,35,229,27" href="javascript:NE()">
              <area shape="poly" coords="196,161,188,151,198,130,196,103,209,102,217,111,213,119,223,125,222,162" href="javascript:CW()">
              <area shape="poly" coords="264,182,255,184,252,188,241,188,240,173,223,173,224,125,214,118,220,109,209,100,205,101,207,84,221,84,235,89,247,102,250,111,257,111,265,123,266,160,261,161,256,167" href="javascript:C()">
              <area shape="poly" coords="291,179,273,182,266,183,257,168,268,161,265,123,256,109,251,106,240,93,261,92,281,123" href="javascript:CE()">
              <area shape="poly" coords="264,239,251,243,236,236,199,169,204,164,222,163,221,175,240,173,239,188,254,189,269,199" href="javascript:SW()">
              <area shape="poly" coords="249,244,264,240,270,199,255,188,268,184,294,181,303,200,302,229,294,269,280,283,233,297" href="javascript:SE()">
            </map><br>
        </td>
        <td align="center" valign="middle" bgcolor="#D7D7D7" >
          <a name="NE">
            <div class="buttonstyle" id="map" style='width: 340px; height: 400px'>
            </div>
          </a></td>
      </tr>
    </table>
     </form>
    </body>

     I hope I have been clear enough in explaining my intent.

  • Re: Reading SQL Server results from asp.net into JavaScript

    09-16-2006, 9:31 PM
    • Loading...
    • mokeefe
    • Joined on 08-20-2006, 5:15 AM
    • Canberra Australia
    • Posts 2,096

    As an alternate to reverse engineering your code, I have provided a working example.

     

    The GetRegionDataJs.aspx renders Javascript back to the client that adds links to a target container in the existing HTML page. The Target Container ID is passed to the page as a parameter.

     

    The page is also coded to know the Javascript function that is available for appending anchors to an existing container. This could all be tightened up, but I am trying to make it as clearer rather than cleaner and potentially more involved.

     

    The LoadJS javascript function is a well know mechanism for adding JS to a page via the header. The JS is executed on load. Just as if it was in orignal page load.

     

    The Page Serving the JS.

     

    ASPX

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetRegionDataJs.aspx.cs" Inherits="spc_GetRegionDataJs" %>

     

    Codebehind/ base class

     

    using System;

    using System.Data;

    using System.Configuration;

    using System.Collections;

    using System.Web;

    using System.Web.Security;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Web.UI.WebControls.WebParts;

    using System.Web.UI.HtmlControls;

     

    public partial class spc_GetRegionDataJs : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            Response.ContentType = "text/javascript";

            string js = this.GetJS(Request.Params["target"]);

            Response.Write(js);

                   

        }

     

        protected string GetJS(string TargetSel) {

     

     

            // Create sample data

            DataTable dt = new DataTable();

            DataColumn textCl = new DataColumn("Text");

            dt.Columns.Add(textCl);

            DataColumn urlCl = new DataColumn("URL");

            dt.Columns.Add(urlCl);

     

            int i = 0;

            string targetContainer = TargetSel;

     

            while (i < 50) {

            DataRow rw = dt.NewRow();

                rw["text"] = "Text " + i.ToString();

                rw["URL"] = "#" + i.ToString();

                dt.Rows.Add(rw);

                i++;

            }

            // end create sample data

     

            System.Text.StringBuilder sBuild = new System.Text.StringBuilder(2);

          

            // you would make better use of the string builder, and also

            // instantiate with an appropriate capacity - it is not fixed, but has better performance if accurate.

     

            foreach(DataRow rw in dt.Rows){

            sBuild.Append("addLinkItem('" + targetContainer + "','" + rw["Text"] + "','" + "http://localhost/garden/mower.aspx?name=" + rw["URL"]);

            sBuild.Append("');");

            }

     

           // output

           return sBuild.ToString();

     

        }

    }

     

     

    Sample page that uses the above page to provide a list of links on a button click.

     

    ASPX

     

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="JSConsumer.aspx.cs" Inherits="spc_Consumer" %>

     

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >

    <head id="Head1" runat="server">

       <title>Dynamic Javascript</title>

    <script type="text/javascript">

       

        // These functions would normally be in a common referenced js file.

       

        // Loads JS from remote page

        function LoadJS(RequestURL){

        if(document.createElement && document.childNodes && newContainer) {

        var scriptElem = document.createElement('script');

          scriptElem.setAttribute('src',RequestURL);

          scriptElem.setAttribute('type','text/javascript');

          document.getElementsByTagName('head')[0].appendChild(scriptElem);

          }// End if

        }//End Function

     

        // This function is called by code returned by the special ASPX page

        // in the sample (by the RequestURL param).

        // You could have mutliple functions for multiple defined actions.

        function addLinkItem(TargetContainerID,ItemText, ItemLink){

        var TargetContainer = document.getElementById(TargetContainerID);

        var newElem = document.createElement('A');

                newElem.setAttribute('href',ItemLink);

                newElem.innerHTML = ItemText;

                TargetContainer.appendChild(newElem);

        }// end function

       

        </script>

        <!-- Style provided for formatting of anchors in new container -->

        <style type="text/css">

     

        #newContainer A {

            margin-top: 2px;

              display: block;

              padding-bottom: 2px;

          width: 100px;

              border-bottom: #696969 1px solid;

        }

     

    </style>

    </head>

    <body>

        <form id="form1" runat="server">

        <input type="button" onclick="LoadJS('http://localhost:8094/spc/GetRegionDataJs.aspx?js=1&target=newContainer&')" value="Load on click"/> 

        <div id="newContainer">

            I am where the new output is to go.

        </div>

        </form>   

    </body>

    <script type="text/javascript">

     

    //Global declarations - must be placed after the page elements

    var newContainer = document.getElementById('newContainer');

     

    // Javascript function that gets dynamic content

    // would load content after document load.

    // LoadJS('http://localhost:8094/spc/GetRegionDataJs.aspx?js=1&target=newcontainer&');

     

    </script>

    </html>

     

    Codebehind

    There is no implemented code behind for this page.

     

    Obviously there is a huge scope for extension here, particularly when considered with server rendered dynamic javascript (item ID’s etc), but this should enable you to meet your stated objectives.

     

    As with any Javascript dependent solution you should consider that javasript is a dependency and what alternatives you offer to clients that don’t support it.

     

    Best of luck,

    Martin.

     

    Rgds,
    Martin.

    For the benefit of all users please mark any post answers as appropriate.
  • Re: Reading SQL Server results from asp.net into JavaScript

    09-20-2006, 9:25 PM
    • Loading...
    • mokeefe
    • Joined on 08-20-2006, 5:15 AM
    • Canberra Australia
    • Posts 2,096
    Did you succeed?
    Rgds,
    Martin.

    For the benefit of all users please mark any post answers as appropriate.
  • Re: Reading SQL Server results from asp.net into JavaScript

    09-20-2006, 11:26 PM
    • Loading...
    • golfvilla
    • Joined on 08-10-2005, 11:57 AM
    • Rockledge, FL
    • Posts 10

    Sorry, I was drawn away on another urgent project. I will try this tomorrow and get back with you. I greatly appreciate your help!!!

    -- Steve

  • Re: Reading SQL Server results from asp.net into JavaScript

    09-21-2006, 9:19 AM
    • Loading...
    • golfvilla
    • Joined on 08-10-2005, 11:57 AM
    • Rockledge, FL
    • Posts 10

    Martin,

     Forgive me but I am confussed about a few things. You state at the bottom of the code that "There is no implemented code behind for this page" yet your page directive for both programs references a code file. The first error produced by Visual Studio is that it can not find the referenced code files. What am I missing?

  • Re: Reading SQL Server results from asp.net into JavaScript

    09-21-2006, 8:00 PM
    • Loading...
    • mokeefe
    • Joined on 08-20-2006, 5:15 AM
    • Canberra Australia
    • Posts 2,096

    To be clearer JSConsumer.aspx.cs does not have any statements in the code behind.

    The other page that is serving the JS has not HTML in the ASPX page.

    Rgds,
    Martin.

    For the benefit of all users please mark any post answers as appropriate.
  • Re: Reading SQL Server results from asp.net into JavaScript

    09-21-2006, 8:15 PM
    • Loading...
    • mokeefe
    • Joined on 08-20-2006, 5:15 AM
    • Canberra Australia
    • Posts 2,096

    Steve

    Having had a moment to review your ealrier detailed post, the other thing to consider is that while I am showing how to get Javascript from the server and execute in a client opened page, as per your original question, it would seem that possibly the easiest way is to dynamically generate the XML for each region and serve that based on the requested page.

    GDownloadUrl("SE_Data.xml", function(data, responseCode) becomes GDownloadUrl("REGION_Data.aspx?param1=x&param2=y", function(data, responseCode)

    This ASPX page could then return appropriate XML content in the same way that I returning text/javascript.

    Do you have a shema definition for the XML? If you do you can use xsd.exe to create a class. You can then populate this with your DB logic and serialise it into the output stream.

    I believe that getting the previous example working is providing a base from which you can later determine which method to use - server rendered JS or XML.

    Regards,

    Martin.

     

    Rgds,
    Martin.

    For the benefit of all users please mark any post answers as appropriate.
  • Re: Reading SQL Server results from asp.net into JavaScript

    10-04-2006, 3:40 PM
    • Loading...
    • golfvilla
    • Joined on 08-10-2005, 11:57 AM
    • Rockledge, FL
    • Posts 10

    Martin,

    As I mentioned in my comment, the code I displayed dynamically writes to an XML file. The problem is that with 8 regions and thousands of suppliers in the database, i