日期:2014-05-18  浏览次数:20411 次

商品分类搜索筛选功能实现
最近自己在做一个小小的网站,想要实现类似于淘宝和京东等商场里的商品分类搜索筛选功能,但是不知道怎么做,小弟新手,莫见怪。在这里想寻下前辈指导一下,希望能讲解一下,感激不尽

------解决方案--------------------
string sql = "select * from products where 1=1 "
if (chkLocation.Checked) sql += " and Location ='" + txtLocation + "' "; //地点
if (chkNew.Checked) sql += " and State = 'New' "; //是否全新
...
------解决方案--------------------
++
探讨

string sql = "select * from products where 1=1 "
if (chkLocation.Checked) sql += " and Location ='" + txtLocation + "' "; //地点
if (chkNew.Checked) sql += " and State = 'New' "; //是否全新
...

------解决方案--------------------
如果用了ORM工具 可以用一个模板类 然后给模板类属性赋值 后台看哪些属性赋值了动态拼sql
下面是一个我自己写的例子 用了linq to sql
C# code

#region ITemplateQuery<news> 成员

        public List<news> TemplateQuery(news queryTemplate)
        {
            using (var context = new DataClasses1DataContext(DBHelper.GetConnectionString()))
            {
                var query = this.GetQuery(queryTemplate, null, null, context);
                return query.OrderByDescending(u => u.news_id).ToList();
            }
        }

        public List<news> TemplateQuery(int startIndex, int pageSize, ref int count, news queryTemplate, DateTime? startDate, DateTime? endDate)
        {
            using (var context = new DataClasses1DataContext(DBHelper.GetConnectionString()))
            {
                var query = this.GetQuery(queryTemplate, startDate, endDate, context);
                count = query.Count();
                return query.OrderByDescending(u => u.news_id).Where(u=>u.news_class!=null).Skip(startIndex * pageSize).Take(pageSize).ToList();
            }
        }

        private  IQueryable<news> GetQuery(news queryTemplate, DateTime? startDate, DateTime? endDate, DataClasses1DataContext context)
        {
            var query = context.news.AsQueryable();
            if (!string.IsNullOrEmpty(queryTemplate.news_title))
            {
                query = query.Where(u => u.news_title.Contains(queryTemplate.news_title));
            }
            if (!string.IsNullOrEmpty(queryTemplate.news_author))
            {
                query = query.Where(u => u.news_author.Equals(queryTemplate.news_author));
            }
            if (!string.IsNullOrEmpty(queryTemplate.news_editor))
            {
                query = query.Where(u => u.news_editor.Equals(queryTemplate.news_editor));
            }
            if (queryTemplate.news_class != null)
            {
                query = query.Where(u => u.news_class == queryTemplate.news_class);
            }
            if (startDate != null)
            {
                query = query.Where(u => u.news_date >= startDate.GetValueOrDefault());
            }
            if (endDate != null)
            {
                query = query.Where(u => u.news_date <= endDate.GetValueOrDefault());
            }
            return query;
        }

        #endregion