c# - 从 _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">×</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 操作方法(不应该),可能是它导致页面刷新和弹出窗口可能会关闭。但它的解决方案是什么。
解决方案
使用您当前的代码,当用户单击锚标记时,浏览器会执行正常的链接单击行为,即导航到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('');
}
})
}
一个建议:如果不是导航链接,考虑使用按钮而不是锚标签。
推荐阅读
- java - Android Java - 我需要根据另一个列表对列表进行排序
- r - 绘制直方图缺少数据
- wolfram-mathematica - Mathematica 列表不会填充
- java - 如何在没有 FXML 的情况下创建自定义复合控件?
- webpack - 如何将 Express 服务器和 PUG 引擎与 Webpack 正确捆绑?
- python - 如何将小部件动态添加到 TabbedPanelItem 中的 GridLayout
- python - Python BlockingIOError: [Errno 11] 发送数据时资源暂时不可用
- git - 将 .gitignore 转换为 .hgignore,反之亦然
- jquery - 使用jQuery动态添加类时如何显示div
- angular - 排序管道总是对大小写敏感(ngx-order-pipe)