Wednesday 5 June 2013

Query string with database

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 ‘db1.vc.example.com’ 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"?>
<configuration>
  <connectionStrings>
    <add name="database" connectionString="Data Source=db1.vc.example.com;Initial Catalog=d1;Integrated Security=False;User ID=user;Password=pass"/>
  </connectionStrings>
  <system.web>
    <customErrors mode="Off"/>
  </system.web>
</configuration>
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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
</head>
<body>
  <asp:SqlDataSource ID="database" runat="server" EnableCaching="true" ConnectionString="<%$ ConnectionStrings:database %>"
    Selectcommand="select [to] as target from mapping where [from] = @id">
    <selectparameters>
      <asp:QueryStringParameter Name="id" QueryStringField="id" />
    </selectparameters>
  </asp:SqlDataSource>
    
  <form id="form" runat="server" style="display: none">
    <asp:ListBox DataSourceId="database" ID="mapping" runat="server" DataTextField="target" DataValueField="target">
    </asp:ListBox>
  </form>
    
  <script type="text/javascript">
    alert("<%= (mapping.Items.Count > 0) ? mapping.Items[0].Value : "" %>");
  </script>
</body>
</html>

No comments:

Post a Comment