萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET MVC 三種彈出視窗實作方式:window.open、Url.Action、jQuery

方式一:input 按鈕 onclick 直接開窗

<input type="button" value="新增部門" 
       onclick="window.open('@Url.Action("AddDpment")', '', 
       'height=180,width=550,fullscreen=no,resizable=yes,scrollbars=no,top=350,left=500')" />

方式二:超連結 a 標籤 + Url.Action 傳參數

<a href="#" onclick="window.open('@Url.Action("EditDpment", "Admin", new { id = item.Department_id })', '', 
       'width=530,height=200,location=no,menubar=no,status=no,scrollbars=no,resizable=no,top=300,left=500')">
    修改部門
</a>
  • 使用 @Url.Action 產生正確路由 URL。
  • 匿名物件 new { id = ... } 自動對應路由參數。

方式三:jQuery 統一管理彈窗邏輯

// 共用函式
function openDialog(url, title, w, h) {
    var left = (screen.width - w) / 2;
    var top = (screen.height - h) / 2;
    return window.open(url, title, 
        `width=${w},height=${h},left=${left},top=${top},resizable=yes,scrollbars=yes`);
}

// 綁定事件 (建議放在 _Layout 或獨立 JS)
$(document).on('click', '.popup-btn', function(e) {
    e.preventDefault();
    openDialog(this.href, '編輯', 600, 400);
});
// 使用
@Html.ActionLink("編輯", "EditDpment", "Admin", new { id = item.Id }, new { @class = "popup-btn" })

表單送出後關閉視窗並更新父頁面

@using (Html.BeginForm("EditGroup", "Admin", FormMethod.Post, new { target = "mainFrame" }))
{
    // ... 表單欄位
    <input type="submit" value="儲存" onclick="setTimeout(() => window.close(), 500);" />
}
  • target="mainFrame" 指定父框架名稱,送出後回應導向父框架。
  • setTimeout(() => window.close(), 500) 給予表單送出時間再關閉彈窗。

選擇建議

方式優點缺點適用場景
inline onclick簡單、無相依程式碼分散、難維護極少數靜態連結
Url.Action + a路由正確、可傳參數仍混雜 JS列表頁編輯/明細按鈕
jQuery 統一關注點分離、易擴充 (置中、模態、動畫)需引入 jQuery專案通用彈窗需求
copyright © 萬盛學電腦網 all rights reserved