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

如何在ASP.NET MVC 5弹窗模态框中实现带结果展示的搜索功能

实现ASP.NET MVC模态框内的异步搜索与结果展示

作为ASP.NET MVC新手,你当前用表单提交+Session传值的方式虽然能跑通,但体验不够流畅(会触发页面刷新),也没法在同一个模态框内无缝展示结果。下面我会一步步教你用jQuery Ajax实现异步搜索,让结果直接显示在模态框里,同时补上你需要的「下拉选择搜索列」「结果行选择链接」功能。

一、技术选型说明

  • jQuery Ajax:用来异步提交搜索请求,避免整页刷新,实现模态框内的局部内容更新。
  • 拆分Partial View:把搜索表单和结果表格拆成两个Partial View,既保证代码复用,也让逻辑更清晰。
  • PartialViewResult:控制器直接返回渲染好的结果表格片段,新手不用写复杂的前端JSON渲染逻辑,上手更快。

二、具体实现步骤

1. 改造搜索表单Partial View(_ClientSearchForm.cshtml)

我们把原来的表单改成Ajax提交,同时添加搜索列下拉选择框和结果展示区域:

@model SmartPhotographer.Models.Client 

<div class="search-form">
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th colspan="2" align="center">Person Details</th>
        </tr>
        <tr>
            <td>搜索列: </td>
            <td>
                <select id="SearchColumn" name="SearchColumn">
                    <option value="FirstName">名字</option>
                    <option value="LastName">姓氏</option>
                    <!-- 可根据需求添加其他搜索列,比如Email、Phone等 -->
                </select>
            </td>
        </tr>
        <tr>
            <td>搜索文本: </td>
            <td>@Html.TextBoxFor(m => m.FirstName, new { id = "SearchText" })</td>
        </tr>
        <tr>
            <td></td>
            <td><button id="SearchBtn" type="button">搜索</button></td>
        </tr>
    </table>
</div>

<!-- 搜索结果展示容器 -->
<div id="SearchResultsContainer" class="mt-3">
    <!-- Ajax返回的结果表格会插入到这里 -->
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
    $(document).ready(function() {
        $("#SearchBtn").click(function() {
            // 获取搜索参数
            const searchColumn = $("#SearchColumn").val();
            const searchText = $("#SearchText").val().trim();

            if (!searchText) {
                alert("请输入搜索内容");
                return;
            }

            // 发起Ajax请求
            $.ajax({
                url: '@Url.Action("SearchClients", "Reservation")',
                type: 'POST',
                data: {
                    SearchColumn: searchColumn,
                    SearchText: searchText
                },
                beforeSend: function() {
                    $("#SearchResultsContainer").html("<p>正在搜索...</p>");
                },
                success: function(result) {
                    $("#SearchResultsContainer").html(result);
                },
                error: function() {
                    $("#SearchResultsContainer").html("<p>搜索出错,请稍后重试</p>");
                }
            });
        });
    });
</script>

2. 创建搜索结果Partial View(_ClientSearchResults.cshtml)

单独做一个Partial View渲染结果表格,每条记录添加选择链接:

@model IEnumerable<SmartPhotographer.Models.Client>

@if (Model != null && Model.Any())
{
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>名字</th>
                <th>姓氏</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var client in Model)
            {
                <tr>
                    <td>@client.FirstName</td>
                    <td>@client.LastName</td>
                    <td>
                        <a href="#" class="select-client-link" 
                           data-client-id="@client.Id" 
                           data-client-name="@client.FirstName @client.LastName">
                            选择
                        </a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}
else
{
    <p>未找到匹配的记录</p>
}

3. 改造控制器的搜索Action

去掉Session传值,直接接收搜索参数,查询后返回结果Partial View:

using System.Linq;
using System.Web.Mvc;
using SmartPhotographer.Models;

namespace SmartPhotographer.Controllers
{
    public class ReservationController : Controller
    {
        private readonly YourDbContext _db = new YourDbContext(); // 替换成你的实际DbContext

        [HttpPost]
        public ActionResult SearchClients(string SearchColumn, string SearchText)
        {
            var clientsQuery = _db.Client.AsQueryable();

            if (!string.IsNullOrEmpty(SearchText))
            {
                // 根据选择的列执行模糊搜索
                switch (SearchColumn)
                {
                    case "FirstName":
                        clientsQuery = clientsQuery.Where(c => c.FirstName.Contains(SearchText));
                        break;
                    case "LastName":
                        clientsQuery = clientsQuery.Where(c => c.LastName.Contains(SearchText));
                        break;
                    // 可添加其他列的搜索逻辑
                }
            }

            // 返回渲染好的结果表格Partial View
            return PartialView("_ClientSearchResults", clientsQuery.ToList());
        }
    }
}

4. 整合到模态框中(以Bootstrap模态框为例)

把搜索表单Partial View放到模态框里,这是ASP.NET项目中最常用的模态框实现方式:

<!-- 模态框触发按钮 -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#ClientSearchModal">
    搜索客户
</button>

<!-- 模态框 -->
<div class="modal fade" id="ClientSearchModal" tabindex="-1" role="dialog" aria-labelledby="ClientSearchModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="ClientSearchModalLabel">搜索客户</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- 加载搜索表单Partial View -->
                @Html.Partial("_ClientSearchForm", new SmartPhotographer.Models.Client())
            </div>
        </div>
    </div>
</div>

<!-- 选择客户后的逻辑(可选) -->
<script>
    $(document).on("click", ".select-client-link", function(e) {
        e.preventDefault();
        // 获取选中的客户信息
        const clientId = $(this).data("client-id");
        const clientName = $(this).data("client-name");
        
        // 这里可以把客户信息回写到父页面的输入框/隐藏域
        $("#ParentPageClientId").val(clientId);
        $("#ParentPageClientName").text(clientName);
        
        // 关闭模态框
        $("#ClientSearchModal").modal("hide");
    });
</script>

三、额外优化建议

  • 表单验证:可以给搜索输入框添加必填、长度限制等前端验证,提升交互体验。
  • 加载动画:把beforeSend里的文字提示换成加载GIF,视觉效果更友好。
  • 分页功能:如果搜索结果较多,可以在结果表格底部添加分页逻辑,避免一次性加载大量数据。

这样改造后,你就能实现一个流畅的模态框搜索功能,搜索结果直接显示在模态框内,完全符合你的需求。

内容的提问来源于stack exchange,提问作者gihan priyankara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:00:58