Pregunta

I have a page that list products from table based on values passed in querystring.
ex:- abc/product.aspx/subcat=Mobile&bnd=Samsung
Here it will display all mobile with brand Samsung

How can i display all mobile irrespective of the brand if bnd is empty or not passed i.e only subcat value is passed.
I need SqlDataSource command to do the same. My current query is as shown below:

<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>
¿Fue útil?

Solución

Code-behind:

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 markup:

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

(Note the removed SelectParameters)

I've never used a SqlDataSource before, but this is similar to what I'd do for an ObjectDataSource. Would the above code work for your scenario?

EDIT : Please note that this method is open to SQL injection attacks, so you ought to validate/sanitize the querystring parameters first.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top