Amin Bakhtiari Far
Amin Bakhtiari Far

Reputation: 156

providing a default value for where statement in linq that uses querystring

lets first see my codes

protected void dsVsl_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
    string query;
    if (Request.QueryString["[VARIABLE]"] != "" && Request.QueryString["[VARIABLE]"] != null)
    {
        query = "";
    }
    else
    {
        query = Request.QueryString["vslCat"];
    } 
    e.Result = (from b in context.tblVessels
                where b.vApproval == true
                where b.vCat == query
                select new
                {
                    b.vAdType,
                    b.vCat,
                    b.vID,
                    b.vAdTitle,
                    b.vAdDesc,
                    b.vBuilder,
                    b.vBuildYear,
                }).ToList();
}

when the first time page loads there is no query-string present so I want to show the results with out any filters but it shows nothingggggggg!!!. and I know that i can place my linq statements in if and else blocks to have two different linq to ADO statements but I don't wanna do that!

Upvotes: 1

Views: 479

Answers (2)

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

In the first query you are checking if b.vCat == "" which is supposedly wrong for all rows you want to gather. Instead put an extra check in your where statement like this:

e.Result = (from b in context.tblVessels
            where b.vApproval == true
            where (query == "" || b.vCat == query)
            select new
            {
                b.vAdType,
                b.vCat,
                b.vID,
                b.vAdTitle,
                b.vAdDesc,
                b.vBuilder,
                b.vBuildYear,
            }).ToList();

Upvotes: 2

Nathan Taylor
Nathan Taylor

Reputation: 24606

Check for a null query value, or a match.

e.Result = (from b in context.tblVessels
            where b.vApproval == true
            where (String.IsNullOrEmpty(query) || b.vCat == query)
            select new
            {
                b.vAdType,
                b.vCat,
                b.vID,
                b.vAdTitle,
                b.vAdDesc,
                b.vBuilder,
                b.vBuildYear,
            }).ToList();

Upvotes: 2

Related Questions