Using ASP.NET to transform a query string parameter via a database

I wanted to have a database table of key/value pairs, and to create an ASP.NET page that would be passed the key in the URL query string and then needed to use the associated value in the JavaScript on that page.

First, the web.config that defines the connection string. It defines a datasource that connects to the host ‘’ and a database on that host called ‘d1’. It also defines the username/password in the connection string, but integrated security may also work if the IIS worker can access the database.

<?xml version="1.0"?>
    <add name="database" connectionString="Data;Initial Catalog=d1;Integrated Security=False;User ID=user;Password=pass"/>
    <customErrors mode="Off"/>

And the aspx page that performs and uses the lookup. It uses SqlDataSource to define the Data Source, with the select parameter coming from the query string. Then there is a ListBox that uses the SqlDataSource as its own Data Source, executing the SQL query. Finally there is the JavaScript block that uses the <%= construct to get the value from the ListBox.

<%@ Page Language=C# Debug=true %>
<%@ Import Namespace=System.Data %>
<%@ Import Namespace=System.Data.SqlClient %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” ““>
<html xmlns=“”>
  <asp:SqlDataSource ID=“database” runat=“server” EnableCaching=“true” ConnectionString=<%$ ConnectionStrings:database %>
    Selectcommand=“select [to] as target from mapping where [from] = @id”>
      <asp:QueryStringParameter Name=“id” QueryStringField=“id” />
  <form id=“form” runat=“server” style=display: none>
    <asp:ListBox DataSourceId=“database” ID=“mapping” runat=“server” DataTextField=“target” DataValueField=“target”>
  <script type=”text/javascript”>
    alert(<%= (mapping.Items.Count > 0) ? mapping.Items[0].Value :  %>);


    Leave a comment