Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 若查询字符串中的一个字段为空且其格式为字符串,则返回表中的所有值_C#_Asp.net_Query String_Sqldatasource - Fatal编程技术网

C# 若查询字符串中的一个字段为空且其格式为字符串,则返回表中的所有值

C# 若查询字符串中的一个字段为空且其格式为字符串,则返回表中的所有值,c#,asp.net,query-string,sqldatasource,C#,Asp.net,Query String,Sqldatasource,我有一个页面,根据querystring中传递的值列出表中的产品。 例如:-abc/product.aspx/subcat=Mobile&bnd=Samsung 在这里,它将显示所有三星品牌的手机 如果bnd为空或未通过,即仅通过subcat值,则如何显示所有手机,而不考虑品牌。 我需要SqlDataSource命令来执行同样的操作。我当前的查询如下图所示: <asp:SqlDataSource ID="SqlDataSource1" runat="server" Connect

我有一个页面,根据querystring中传递的值列出表中的产品。
例如:-abc/product.aspx/subcat=Mobile&bnd=Samsung
在这里,它将显示所有三星品牌的手机

如果bnd为空或未通过,即仅通过subcat值,则如何显示所有手机,而不考虑品牌。
我需要SqlDataSource命令来执行同样的操作。我当前的查询如下图所示:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:shoppingConnectionString2 %>" 
    SelectCommand="SELECT * FROM [ProductDetails] WHERE (([Sub_category] = @Sub_category) AND ([Brand] = @Brand OR @Brand IS NULL))" 
    onselecting="SqlDataSource1_Selecting">
    <SelectParameters>
        <asp:QueryStringParameter Name="Sub_category" QueryStringField="subcat" 
            Type="String" DefaultValue="&quot; &quot;" />
        <asp:QueryStringParameter Name="Brand" QueryStringField="bnd" Type="String" 
            DefaultValue="IS NULL" ConvertEmptyStringToNull="True" />
    </SelectParameters>
</asp:SqlDataSource>

代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string subcat = Request.QueryString["subcat"];
        string bnd = Request.QueryString["bnd"];

        string query = "SELECT * FROM [ProductDetails] WHERE ([Sub_category] = " + subcat + ")";
        if (!String.IsNullOrEmpty(bnd))
        {
            query += " AND ([Brand] = " + bnd + ")";
        }                

        SqlDataSource1.SelectCommand = query;                
    }
}
HTML标记:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:shoppingConnectionString2 %>" 
    SelectCommand="SELECT * FROM [ProductDetails]" 
    onselecting="SqlDataSource1_Selecting">
</asp:SqlDataSource>

(注意已删除的SelectParameters)

我以前从未使用过SqlDataSource,但这与我对ObjectDataSource所做的类似。上述代码是否适用于您的场景


编辑:请注意,此方法容易受到SQL注入攻击,因此您应该首先验证/清理querystring参数。

只需从SQL命令中检查参数,它会更干净。这将使您不用编写复杂的sql命令,并相应地更改您的命令。哇,真的非常感谢您的帮助,而且我不知道我也可以用代码来处理这个问题。真的非常感谢。它们只是有点变化,因为我的值是字符串,所以它将是“+subcat+”。