我一直在这个网站上问了几个问题,并且得到了很多小问题的答案,但我现在正试图把整个事情拼凑起来。
我有一个页面,其中显示了我在数据库中拥有的所有属性。不过,我需要找到一种方法来优化这些结果,例如,只显示有 4 间卧室的房产等。问题是,我不知道搜索词中可能有多少变量。所以这里有一个例子。
- 用户可能想查看所有只有 4 间卧室的房产
- 用户可能希望查看所有具有 4 间卧室和 3 间浴室并睡 8 人等的房产。
我决定从查询字符串 ?numbedrooms=4&?numbathrooms=3 中提取所有变量
这是我到目前为止的代码,但它不起作用:
@{
var db = Database.Open("StayInFlorida");
IEnumerable<dynamic> queryResults;
int numBedrooms = Request.QueryString["numBedrooms"].AsInt();
int numBathrooms = Request.QueryString["numBathrooms"].AsInt();
int sleeps = 0;
List<int> argList = new List<int>();
if (Request.QueryString["sleeps"].IsInt())
{
sleeps = Request.QueryString["sleeps"].AsInt();
}
int numOfArguments = 0;
string selectQueryString = "SELECT * FROM PropertyInfo ";
if (numBedrooms != 0)
{
argList.Add(numBedrooms);
selectQueryString += "WHERE numBedrooms = @0 ";
numOfArguments++; //increment numOfArguments by 1
}
if (numBathrooms != 0)
{
argList.Add(numBathrooms);
if (numOfArguments == 0)
{
selectQueryString += "WHERE numBathrooms = @0 ";
}
else
{
selectQueryString += "AND numBathrooms = @" + numOfArguments + " ";
}
numOfArguments++;
}
if (sleeps != 0)
{
argList.Add(sleeps);
if (numOfArguments == 0)
{
selectQueryString += "WHERE sleeps = @0 ";
}
else
{
selectQueryString += "AND sleeps = @" + numOfArguments + " ";
}
numOfArguments++;
}
selectQueryString += "ORDER BY numBedrooms DESC"; //Adjust this order by clause how you see fit.
int[] argArray = argList.ToArray();
if (argArray.Length > 0)
{
queryResults = db.Query(selectQueryString, argArray); //stores a dynamic list to 'queryResults' which can later be easily iterated through with a 'foreach' list and written to the page with razor.
}
}
<!--Results Start-->
@foreach(var row in queryResults){
<div class="container">
<h4><a href="/property.cshtml?propertyid=@row.PropertyID">@row.PropertyName</a></h4>
<h5>Bedrooms: @row.NumBedrooms Bathrooms: @row.NumBathrooms Sleeps: @row.NumSleeps</h5>
</div>
}
<!--Results Finish-->
所以为了澄清,我需要找到一种方法来检查每个搜索查询是否有一个查询字符串条目,如果有,将其附加到 SQL 语句中以查看所有匹配的结果?