-2

我有一个下拉列表,它产生以下内容:

SiteId 的可能值:

 "Select Site"
 "1"
 "2"
 "3"
 "4"

请注意,选择站点是默认值:

    <asp:DropDownList ID="ddlSite" DataSourceID = "siteDS" runat="server" OnSelectedIndexChanged="ddlSite_SelectedIndexChanged" AutoPostBack="true" DataTextField="SiteName" 
            DataValueField="SiteId" AppendDataBoundItems="true">
            <asp:ListItem>Select Site</asp:ListItem>
    </asp:DropDownList>

我有以下查询,但不确定是否有更好的方法

     // this checks to see if the value is Select Site or an actual siteid (1,2,3)
     int siteID = 0;
     int Site;
     bool result = Int32.TryParse(ddlSite.SelectedValue, out Site);
     if (result)
     {
        siteID = Site;
     }


     if (result)
     {
        NTDS.SelectCommand = "SELECT *  FROM [tbl1] where siteId = " + siteID;
     }
     else
     {
        NTDS.SelectCommand = "SELECT *  FROM [tbl1]";
     }

我之所以有 if else 是因为我们如果用户选择:选择站点,我不想执行 SELECT,因为没有值为 Select Site 的 siteId。

有没有更有效的方法来做到这一点?

4

2 回答 2

3

首先,我建议阅读有关Sql Injections的内容,并且您应该真正参数化您的查询。

其次,由于您同时拥有 DataText 和 DataValue 属性,因此您可以将“SelectSite”作为Text属性,并将Value其设为 0 或 -1(或为空)。

无论哪种方式,您都可以执行以下操作:

if (Int32.TryParse(ddlSite.SelectedValue, out Site) && Site  > 0)
{
    // Parameterized SELECT
}
else
{
  ...
}

不需要 SiteSiteId

于 2013-03-28T17:05:59.047 回答
1
// your initial item or better off you can add a client side validator
// preventing them from submitting the page with the initial value, also call Page.IsValid on server side to make sure they didn't hacked your client side validation.
if (ddlSite.SelectedIndex != 0)
{
   var siteId = 0;
   if (int.TryParse(ddlSite.SelectedValue, out siteId)
   {
      // then here build a helper for adding conditions if siteId is present.
      // try using parameterized queries for avoiding sql injection.
   }
   else
   {
      // call your same helper without siteId and it should be smart enough to
      // return a query without where clause.
   }
}

这里有更多关于参数化查询的信息。

于 2013-03-28T17:11:00.217 回答