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

Bootstrap Notify onClose传参问题:ASP.NET后台生成通知需传Alert ID

How to Pass Alert ID from ASP.NET Backend to Bootstrap-Notify for Database Updates

Alright, let's tackle this problem—you've got bootstrap-notify working smoothly with your ASP.NET project, notifications stay open until manual close, and your Web method to update the database is ready to go. The missing piece is getting that alert ID from your backend to the notification so you can reference it when the user closes the alert. Here's how to make it happen:

1. Embed the Alert ID in the Notification from the Backend

When generating the bootstrap-notify script in your C# backend, you need to inject the alert ID directly into the notification. You have two clean ways to do this:

Option A: Use a Data Attribute (Clean Separation of Concerns)

Attach the alert ID as a data attribute to the notification's HTML content—this makes it easy to grab later when the close event fires:

// Grab your alert ID from the database (example value shown)
int alertId = 456;
// Sanitize values to prevent XSS vulnerabilities
string safeAlertId = HttpUtility.HtmlEncode(alertId.ToString());
string safeNotificationText = HttpUtility.HtmlEncode("Your notification message here");

// Build the bootstrap-notify script with embedded data attribute
string notifyScript = $"$.notify('<div data-alert-id=\"{safeAlertId}\">{safeNotificationText}</div>', {{ delay: 0, type: 'info', allow_dismiss: true }});";

// Register the script to run on the frontend (use unique ID to avoid conflicts)
ClientScript.RegisterStartupScript(this.GetType(), $"Alert_{alertId}", notifyScript, true);

Option B: Pass ID Directly to a Close Callback

If you prefer a more direct approach, pass the alert ID straight to a custom function when the notification closes:

int alertId = 456;
string safeNotificationText = HttpUtility.HtmlEncode("Your notification message here");

// Inject the alert ID into the onClosed callback
string notifyScript = $"$.notify('<div>{safeNotificationText}</div>', {{ delay: 0, type: 'info', allow_dismiss: true, onClosed: function() {{ markAlertAsRead({alertId}); }} }});";

ClientScript.RegisterStartupScript(this.GetType(), $"Alert_{alertId}", notifyScript, true);

2. Capture the Alert ID on Close & Call Your Web Method

Now you need to handle the close event, retrieve the alert ID, and send it to your Web method to update the database.

For Option A (Data Attribute):

Add this JavaScript to your frontend (in a script tag or external JS file):

// Listen for the bootstrap-notify close event across the document
$(document).on('closed.bs.notify', function(event) {
    // Extract the alert ID from the data attribute
    const alertId = $(event.target).find('[data-alert-id]').data('alert-id');
    
    if (alertId) {
        // Call your Web method to mark the alert as read
        $.ajax({
            type: "POST",
            url: "YourPage.aspx/MarkAlertAsRead", // Replace with your actual page/method path
            data: JSON.stringify({ alertId: alertId }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                console.log(`Alert ${alertId} marked as read successfully`);
                // Optional: Add user feedback here if needed
            },
            error: function(xhr, status, error) {
                console.error(`Failed to update alert ${alertId}:`, error);
                // Optional: Handle error feedback here
            }
        });
    }
});

For Option B (Direct Callback):

Define the markAlertAsRead function in your frontend:

function markAlertAsRead(alertId) {
    $.ajax({
        type: "POST",
        url: "YourPage.aspx/MarkAlertAsRead",
        data: JSON.stringify({ alertId: alertId }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            console.log(`Alert ${alertId} updated successfully`);
        },
        error: function(err) {
            console.error(`Error updating alert ${alertId}:`, err);
        }
    });
}

Quick Key Notes

  • XSS Protection: Always sanitize dynamic values (like alert IDs and notification text) with HttpUtility.HtmlEncode to avoid cross-site scripting attacks.
  • Unique Script IDs: Use a unique ID (like Alert_{alertId}) when registering startup scripts to prevent overwriting other notifications.
  • Web Method Setup: Ensure your Web method is decorated with [WebMethod] and is a public static method in your code-behind for accessibility.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:23:03