作成したWebアプリケーションについても同様のことをしました。asp:SqlDatasourceのOnSelectingイベント(分離コードでselectコマンドを動的に構築する代わりにこれを使用することをお勧めします)を利用して、selectコマンドのパラメーターを動的に調整できます。
これがこれを行うための最適な方法であるかどうかはわかりませんが、機能します。
私のマークアップは次のようになりました(GridViewタグが簡略化されています):
<asp:SqlDataSource ID="SelectItemsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:hubConnectionString %>"
ProviderName="<%$ ConnectionStrings:hubConnectionString.ProviderName %>"
SelectCommand="SELECT itemEntity.id, itemEntity.name, itemEntity.filename, itemEntity.type, itemEntity.added, userEntity.name FROM item AS itemEntity
LEFT OUTER JOIN USER AS userEntity ON itemEntity.uploader = userEntity.id WHERE itemEntity.type like @type ORDER BY itemEntity.added DESC"
OnSelecting="onItemSelecting">
<SelectParameters>
<asp:Parameter Name="@type" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="ItemGrid" runat="server" DataSourceID="SelectItemsDataSource"/> // Simplified
OnSelecting属性に注意してください。
次に、コードビハインドでOnSelectingイベントを処理できます。
protected void onItemSelecting(object sender, SqlDataSourceSelectingEventArgs e)
{
// Type value NOT given and parameter exists - Set wildcard
if (Request.QueryString["type"] == null && e.Command.Parameters.Contains("@type"))
{
e.Command.Parameters["@type"].Value = "%";
return;
}
if (Request.QueryString["type"] != null && e.Command.Parameters.Contains("@type"))
e.Command.Parameters["@type"].Value = Request.QueryString["type"];
}
Command.ParametersメソッドはSQLインジェクションで安全だと思います。そうでない場合は、誰かが私を修正してください。