最近在做一个Asp.net MVC的项目,里面用部分视图页弹层,感觉很不爽,用着别扭。在前后端分离的项目里,我们肯定用封装好的前端UI库了,比如element ui,但是 Asp.net MVC的项目里面集成这个比较困难......
就找了个前端弹层组件 SweetAlert2 点击转到官网
还有一个 SweetAlert 2 全网最详细的使用方法
我自己测试过的例子在下面,功能非常全面,我觉得完全够用了,唯一不好得就是 html 要拼接字符串......
// 定义表单提交函数
function submitForm(formData) {
// 使用 AJAX 将表单数据发送到控制器
$.ajax({
url: '/SampleController/SubmitForm',
type: 'POST',
data: JSON.stringify(formData), // 将对象转换为 JSON 字符串
contentType: 'application/json', // 设置请求的内容类型为 JSON
success: function(response) {
Swal.fire({
title: '表单提交成功',
text: response.message,
icon: 'success',
confirmButtonText: '确定', // 确定按钮文本
showConfirmButton: false, // 不显示确定按钮
timer: 2000, // 定时器,2秒后自动关闭对话框
onClose: function() {
// 对话框关闭后的回调函数
// 可以在这里执行其他操作
}
});
},
error: function(xhr, status, error) {
Swal.fire({
title: '错误',
text: '表单提交失败',
icon: 'error',
confirmButtonText: '确定' // 确定按钮文本
});
}
});
}
// 当按钮被点击时,打开 SweetAlert2 对话框
document.getElementById('openDialogButton').addEventListener('click', function() {
const fixedWidth = '80px'; // 定义固定宽度
const htmlContent = `
<div style="display: flex; align-items: center;">
<label for="input1" style="width: ${fixedWidth};">内容1:</label>
<input type="text" id="input1" name="input1" class="swal2-input">
</div>
<div style="display: flex; align-items: center;">
<label for="input2" style="width: ${fixedWidth};">内容2:</label>
<input type="text" id="input2" name="input2" class="swal2-input">
</div>
`;
Swal.fire({
title: '填写内容',
html: htmlContent,
customClass: {
container: 'my-swal-container' // 添加自定义 CSS 类名
},
focusConfirm: false,
cancelButtonText: '取消', // 取消按钮文本
showCancelButton: true, // 显示取消按钮
confirmButtonText: '确定', // 确定按钮文本
showCloseButton: true, // 显示关闭按钮
preConfirm: function() {
const input1Value = Swal.getPopup().querySelector('#input1').value;
const input2Value = Swal.getPopup().querySelector('#input2').value;
// 验证用户输入
if (!input1Value || !input2Value) {
Swal.showValidationMessage('请填写所有内容');
return false;
}
// 封装表单数据为对象
const formData = {
input1: input1Value,
input2: input2Value
};
// 调用表单提交函数
submitForm(formData);
// 返回一个 Promise 对象,用于关闭对话框
return Promise.resolve();
}
});
});