Bootstrap Notify onClose传参问题:ASP.NET后台生成通知需传Alert ID
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.HtmlEncodeto 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

