You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC搜索栏筛选实现求助:同页展示结果

ASP.NET Core MVC + ADO.NET 实现房源筛选与分页展示

一、更新视图:添加筛选下拉菜单

替换原有搜索表单,增加区域、价格区间等筛选控件,确保表单提交时携带筛选与分页参数:

@model IEnumerable<eHouse.Models.RentModel>
<div class="navbar-left-section">
    <form method="get" asp-action="Rent">
        <div class="wrap">
            <!-- 区域筛选下拉框 -->
            <select name="area" class="filter-select">
                <option value="">所有区域</option>
                <option value="南区">南区</option>
                <option value="北区">北区</option>
                <!-- 根据数据库实际区域数据填充选项 -->
            </select>
            <!-- 价格区间筛选下拉框 -->
            <select name="priceRange" class="filter-select">
                <option value="">所有价格</option>
                <option value="0-1000">1000元以下</option>
                <option value="1000-2000">1000-2000元</option>
                <option value="2000+">2000元以上</option>
            </select>
            <!-- 关键词搜索框 -->
            <input type="text" name="keyword" class="searchTerm" style="width: 700px; color:#000000; text-align: left;" placeholder="搜索房源标题/描述">
            <button type="submit" class="searchButton" >
                <i class="fa fa-search"></i>
            </button>
        </div>
        <!-- 隐藏字段保存当前页码,避免筛选后回到第一页 -->
        <input type="hidden" name="PageNumber" value="@ViewBag.CurrentPage" />
    </form>
</div>

二、修改控制器:整合筛选逻辑与分页

更新Rent方法,接收筛选参数,在数据查询阶段应用筛选规则,同时保留分页逻辑:

public IActionResult Rent(int PageNumber = 1, string area = "", string priceRange = "", string keyword = "")
{
    // 获取经过筛选的房源数据
    var data = rdb.GetFilteredHouses(area, priceRange, keyword);
    
    int pageSize = 6;
    // 分页处理
    var paginatedData = data.Skip((PageNumber - 1) * pageSize).Take(pageSize).ToList();
    
    // 传递分页与筛选参数到视图
    ViewBag.TotalPages = Math.Ceiling((double)data.Count() / pageSize);
    ViewBag.CurrentPage = PageNumber;
    ViewBag.Area = area;
    ViewBag.PriceRange = priceRange;
    ViewBag.Keyword = keyword;

    return View(paginatedData);
}

三、实现ADO.NET筛选查询(数据访问层)

在数据访问类中新增GetFilteredHouses方法,动态构建安全的SQL查询,在数据库层面完成筛选:

public List<RentModel> GetFilteredHouses(string area, string priceRange, string keyword)
{
    List<RentModel> houses = new List<RentModel>();
    // 基础SQL语句,用1=1简化条件拼接
    string sql = "SELECT * FROM RentHouses WHERE 1=1";
    List<SqlParameter> parameters = new List<SqlParameter>();

    // 区域筛选
    if (!string.IsNullOrEmpty(area))
    {
        sql += " AND Area = @Area";
        parameters.Add(new SqlParameter("@Area", area));
    }

    // 价格区间筛选
    if (!string.IsNullOrEmpty(priceRange))
    {
        string[] range = priceRange.Split('-');
        if (range.Length == 2)
        {
            if (range[0] == "0")
            {
                sql += " AND Price <= @MaxPrice";
                parameters.Add(new SqlParameter("@MaxPrice", decimal.Parse(range[1])));
            }
            else
            {
                sql += " AND Price >= @MinPrice AND Price <= @MaxPrice";
                parameters.Add(new SqlParameter("@MinPrice", decimal.Parse(range[0])));
                parameters.Add(new SqlParameter("@MaxPrice", decimal.Parse(range[1])));
            }
        }
        else if (priceRange == "2000+")
        {
            sql += " AND Price >= 2000";
        }
    }

    // 关键词模糊筛选(标题或描述)
    if (!string.IsNullOrEmpty(keyword))
    {
        sql += " AND (Tittle LIKE @Keyword OR Descrip LIKE @Keyword)";
        parameters.Add(new SqlParameter("@Keyword", $"%{keyword}%"));
    }

    // ADO.NET执行查询
    using (SqlConnection conn = new SqlConnection(yourConnectionString)) // 替换为你的数据库连接字符串
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.Parameters.AddRange(parameters.ToArray());
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    houses.Add(new RentModel
                    {
                        id = (int)reader["Id"],
                        tittle = reader["Tittle"].ToString(),
                        price = (decimal)reader["Price"],
                        bedroom = (int)reader["Bedroom"],
                        bathroom = (int)reader["Bathroom"],
                        descrip = reader["Descrip"].ToString(),
                        pic1 = reader["Pic1"].ToString()
                        // 映射其他需要的字段
                    });
                }
            }
        }
    }

    return houses;
}

四、分页控件适配筛选参数

如果视图中有分页按钮,需确保点击分页时携带当前筛选参数,避免筛选条件丢失:

<div class="pagination">
    @for (int i = 1; i <= ViewBag.TotalPages; i++)
    {
        <a asp-action="Rent" 
           asp-route-PageNumber="@i"
           asp-route-area="@ViewBag.Area"
           asp-route-priceRange="@ViewBag.PriceRange"
           asp-route-keyword="@ViewBag.Keyword"
           class="@(i == ViewBag.CurrentPage ? "active" : "")">@i</a>
    }
</div>

内容的提问来源于stack exchange,提问作者Qasim Asghar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:25:29