首页 > 解决方案 > 从 _Layout 调用时无法将部分视图加载为模态

问题描述

在我的 Core 2.0 项目中,当从 _Layout.cshtml 调用时,我试图将部分视图加载到模态 div,但没有任何反应。单击创建新用户时,我正在尝试在模式弹出窗口上加载部分视图。下面是代码-

//_Layout.cshtml

<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
<li><a href="/" onclick="CreateUser()">Create New User</a></li>

//首页的Index.cshtml

<div class="modal fade" id="AppointmentSchedule" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header btn-primary">
                <h5 class="modal-title" id="AppointmentModalLabel"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="ScheduleAppointment"></div>
        </div>
    </div>
</div>

//Javascript

function CreateUser() {
            var url = appSetting + "Home/CreateUser";
            $.ajax({
                type: "GET",
                contentType: "application/json",
                url: url,
                data: null,
                dataType: "html",
                async: false,
                success: function (data) {
                    $("#ScheduleAppointment").html('');
                    $("#ScheduleAppointment").html(data);
                    $("#AppointmentSchedule").modal('show');
                },
                error: function (result) {
                    $("#divScheduleAppointment").html('');
                }
            })
        }

//家庭控制器

  public ActionResult CreateUser()
      {
        return PartialView("_CreateUserHome");
      }

在调试时,我意识到在 Ajax 成功后它调用 Home 控制器的 Index 操作方法(不应该),可能是它导致页面刷新和弹出窗口可能会关闭。但它的解决方案是什么。

标签: c#asp.net-coreasp.net-core-mvc

解决方案


使用您当前的代码,当用户单击锚标记时,浏览器会执行正常的链接单击行为,即导航到href单击的链接元素的属性值。如果你想显示模式对话框而不是那个,你应该阻止这种默认行为。

您可以将event对象传递给CreateUser方法

<a href="/" onclick="CreateUser(event)">Create New User</a>

并在您的方法中调用该preventDefault方法,这将停止正常的链接点击行为(导航到该href值)

function CreateUser(e)
{
    e.preventDefault();

    var url = appSetting + "Home/CreateUser";
    $.ajax({
        type: "GET",
        url: url,
        success: function (data)
        {
            $("#ScheduleAppointment").html(data);
            $("#AppointmentSchedule").modal('show');
        },
        error: function (result)
        {
            $("#divScheduleAppointment").html('');
        }
    })
}

一个建议:如果不是导航链接,考虑使用按钮而不是锚标签。


推荐阅读