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

ASP.NET Core中jQuery渲染Partial View后按钮点击失效问题

问题解决:点击按钮无法重新加载Partial View

核心问题原因

你当前使用$detailDiv.replaceWith(data)替换了整个detailsDiv元素,导致第一次渲染后页面中不再存在ID为detailsDiv的容器,后续点击按钮时无法找到该元素进行更新,因此按钮看似失效。

解决方案一:保留Partial View并恢复按钮功能

只需将replaceWith改为html,这样只会替换detailsDiv内部的内容,而保留容器本身,按钮就能持续生效,支持输入新ID替换现有Partial View:

修正后的View脚本部分

@section Scripts {
    <script src="@Url.Content("//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.js")"></script>
    <script type="text/javascript">
        $(document).on('click', '.js-load-partial', function (evt) {
            evt.preventDefault();
            var $detailDiv = $('#detailsDiv'),
                url = $(this).data('url');
            url = url.replace("param", $("#EmpId").val());
            $.get(url, function(data) {
                // 替换为html()而非replaceWith()
                $detailDiv.html(data);
            });
        });
    </script>
}

解决方案二:禁用按钮并添加刷新按钮(备选)

如果确实需要禁用搜索按钮,可在第一次点击后添加禁用状态,并新增一个刷新页面的按钮:

修改后的View按钮部分

<p>
    Find Employee By ID:
    <input type="text" id="EmpId" name="EmpId" />
    <button data-url='@Url.Action("PartialIndex","StaffDetailsVM", new { id = "param" } )' class="js-load-partial">Search</button>
    <!-- 新增刷新按钮,初始隐藏 -->
    <button id="refreshBtn" class="btn btn-secondary" style="display:none;" onclick="location.reload()">Refresh Page</button>
    <a class="btn btn-info" style="margin: 3px; display:inline-block; float: right" asp-controller="Employees" asp-action="Index">Full Employee List</a>
</p>

对应修改的脚本

@section Scripts {
    <script src="@Url.Content("//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.js")"></script>
    <script type="text/javascript">
        $(document).on('click', '.js-load-partial', function (evt) {
            evt.preventDefault();
            var $btn = $(this);
            var $detailDiv = $('#detailsDiv'),
                url = $btn.data('url');
            url = url.replace("param", $("#EmpId").val());
            // 禁用搜索按钮
            $btn.prop('disabled', true).addClass('disabled');
            // 显示刷新按钮
            $('#refreshBtn').show();
            $.get(url, function(data) {
                $detailDiv.html(data);
            });
        });
    </script>
}

完整代码参考

View(修正后)

@model IEnumerable<MISDataRepo.Models.Employee>

<style>
    small {
        color: red;
        font-weight: bold;
    }
</style>

<h1>Staff Details</h1>

<p>
    Find Employee By ID:
    <input type="text" id="EmpId" name="EmpId" />
    <button data-url='@Url.Action("PartialIndex","StaffDetailsVM", new { id = "param" } )' class="js-load-partial">Search</button>
    <a class="btn btn-info" style="margin: 3px; display:inline-block; float: right" asp-controller="Employees" asp-action="Index">Full Employee List</a>
</p>
<br />

<div id="detailsDiv"></div>

@section Scripts {
    <script src="@Url.Content("//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.js")"></script>
    <script type="text/javascript">
        $(document).on('click', '.js-load-partial', function (evt) {
            evt.preventDefault();
            var $detailDiv = $('#detailsDiv'),
                url = $(this).data('url');
            url = url.replace("param", $("#EmpId").val());
            $.get(url, function(data) {
                $detailDiv.html(data);
            });
        });
    </script>
}

Partial View 1(ID存在时)

@using MISDataRepo.ViewModels;
@model StaffDetailsVM;

@{
    ViewData["Title"] = "Employee Details";
}
<hr />
<h1>Employee Details</h1>

<div>
    <h4>@ViewBag.EmpName</h4>
    <h4 style="font-weight:bold">PID: @ViewBag.EmpId</h4>
    <hr />
    <dl class="row">
        <dt class="col-sm-2">Grade</dt>
        <dd class="col-sm-10">@ViewBag.EmpGrade</dd>
        <dt class="col-sm-2">Area</dt>
        <dd class="col-sm-10">@ViewBag.EmpArea</dd>
        <dt class="col-sm-2">Team</dt>
        <dd class="col-sm-10">@ViewBag.EmpTeam</dd>
    </dl>
</div>
<br />
<a class="btn btn-success btn-sm" style="margin: 2px" asp-controller="Employees" asp-action="Edit" asp-route-id="@ViewBag.EmpId">Edit Employee Details</a>
<hr />

<h1>Contracted Hours</h1>

<table class="table table-bordered table-hover table-striped">
    <thead class="thead-dark">
        <tr>
            <th>Mon</th>
            <th>Tue</th>
            <th>Wed</th>
            <th>Thu</th>
            <th>Fri</th>
            <th>Sat</th>
            <th>Sun</th>
            <th>Total Weekly Hours</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.ContractedHours)
        {
            <tr>
                <td>@Html.DisplayFor(modelItem => item.Mon)</td>
                <td>@Html.DisplayFor(modelItem => item.Tue)</td>
                <td>@Html.DisplayFor(modelItem => item.Wed)</td>
                <td>@Html.DisplayFor(modelItem => item.Thu)</td>
                <td>@Html.DisplayFor(modelItem => item.Fri)</td>
                <td>@Html.DisplayFor(modelItem => item.Sat)</td>
                <td>@Html.DisplayFor(modelItem => item.Sun)</td>
                <td>@Html.DisplayFor(modelItem => item.TotalHours)</td>
                <td>
                    <a class="btn btn-success btn-sm" style="margin: 2px" asp-controller="ContractedHours" asp-action="Edit" asp-route-id="@item.EmployeeId">Edit</a>
                </td>
            </tr>
        }
    </tbody>
</table>
<hr />

<h1>Access Levels</h1>

<table class="table table-bordered table-hover table-striped">
    <thead class="thead-dark">
        <tr>
            <th>Access Level</th>
            <th>App</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.UserAccessLevel)
        {
            <tr>
                <td>@Html.DisplayFor(modelItem => item.AccessLevel.AccessLevelName)</td>
                <td>@Html.DisplayFor(modelItem => item.AppLibrary.AppName)</td>
                <td><a class="btn btn-success btn-sm" style="margin: 2px" asp-controller="UserAccessLevels" asp-action="Edit" asp-route-id="@item.UserAccessLevelId">Edit</a></td>
            </tr>
        }
    </tbody>
</table>
<br />
<a class="btn btn-primary btn-sm" style="margin: 2px" asp-controller="UserAccessLevels" asp-action="Create" asp-route-empId="@ViewBag.EmpId">Create Access Level for User</a>

Partial View 2(ID不存在时)

@using MISDataRepo.ViewModels;
@model StaffDetailsVM;

@{
    ViewData["Title"] = "Invalid ID";
}
<style>
    small {
        color: red;
        font-weight: bold;
    }
</style>

<p>
    <br /><small style="margin-left: 100px">@ViewBag.Err</small>
</p>

Controller

public IActionResult PartialIndex(int id)
{
    if (!EmployeeExists(id))
    {
        ViewBag.EmpId = id;
        ViewBag.Err = "*Employee ID '" + id + "' does not exist in database, please review!";
        return PartialView("_invalidID");
    }

    var employee = _context.Employee.Include(e => e.Area).Include(e => e.Grade).Include(e => e.Team).Where(e => e.EmployeeId == id);

    ViewBag.EmpId = id;
    ViewBag.EmpName = employee.First().FullName;
    ViewBag.EmpGrade = employee.First().Grade.GradeName;
    ViewBag.EmpArea = employee.First().Area.AreaName;
    ViewBag.EmpTeam = employee.First().Team.TeamName;

    StaffDetailsVM vm = new StaffDetailsVM
    {
        ContractedHours = GetContractedHours(id),
        UserAccessLevel = GetUserAccessLevel(id)
    };

    return PartialView("_partialIndex", vm);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:25:39