网站只能搜索或排序数据库中的数据

时间:2015-12-16 22:36:07

标签: c# sql razor

我为大学创建了一个基本的电子商务网站,我在排序和搜索我的产品表时遇到问题我的页面显示产品很好。 该网站是在visual studio 2012中使用razor v2标记和C#制作的。

@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Store";
    var db = Database.Open("StarterSite");
    string sql = "";

    switch (Request["sort"])
    {
        case "PriceASC":
            sql = "SELECT * FROM Products order by Product_Price ASC";
            break;
        case "PriceDESC":
            sql = "SELECT * FROM Products order by Product_Price DESC";
            break;
        default:
            sql = "SELECT * FROM PRODUCTS ORDER BY Product_ID";
            break;
    }

    if (Request["search"] != "")
    {
        sql = "SELECT * FROM Products where Product_Keywords like '%" + Request["search"] + "%'";
    }
}

这是我正在使用的代码,它们都是独立工作的,但当我把它们放在一起时,无论哪一个是第二个,接管并打破第一个。我已多次交换它们来测试这个,关于如何让它们很好地协同工作的任何想法?

1 个答案:

答案 0 :(得分:1)

将它们组合起来不再有效的原因是因为您要覆盖在第一步中进行的查询。我要做的是将这个过程分解成几部分。

//declare your variable.  I added a connection and command so I can include parameters in the process.
string orderBy = "";
string whereClause = "";
string sql = "";

//create your order by clause
switch (Request["sort"])
{
    case "PriceASC":
        orderBy = "order by Product_Price ASC";
        break;
    case "PriceDESC":
        orderBy = "order by Product_Price DESC";
        break;
    default:
        orderBy = "ORDER BY Product_ID";
        break;
}

//create your where clause.  
if (!string.IsNullOrEmpty(Request["search"])) // forgot the ! here
{
    whereClause = string.Format(" where Product_Keywords like '%{0}%'", Request["search"]); // very unsafe to plug this in.  should use parameter

}

sql = string.Format("SELECT * FROM Products{0} {1}",whereClause, orderBy); //build your query string.  if no search parameter was given the where clause will be blank, but the order by will still exist.

@foreach (var row in db.Query(sql))
{
    //some code here
}