如何实现点击抽奖按钮时,同步在另一页面表格展示抽奖结果
Hey there! Let's figure out how to make your lottery system show results on both the current page and another page's table when the draw button is clicked. Since you're working with C#, I'll cover the two most common scenarios you might be in: web apps (like ASP.NET) and desktop apps (WinForms/WPF).
The best way to get real-time updates across pages is using SignalR (Microsoft's library for real-time web communication). Here's a step-by-step breakdown:
Step 1: Install SignalR
First, add the SignalR NuGet package to your project. For traditional ASP.NET:
Install-Package Microsoft.AspNet.SignalR
For ASP.NET Core:
Install-Package Microsoft.AspNetCore.SignalR
Step 2: Create a SignalR Hub
This hub will handle sending the lottery result to connected clients:
// For traditional ASP.NET using Microsoft.AspNet.SignalR; public class LotteryHub : Hub { // Method to send results to all connected clients public void BroadcastLotteryResult(string result) { Clients.All.ReceiveLotteryResult(result); } } // For ASP.NET Core using Microsoft.AspNetCore.SignalR; public class LotteryHub : Hub { public async Task BroadcastLotteryResult(string result) { await Clients.All.SendAsync("ReceiveLotteryResult", result); } }
Step 3: Configure SignalR
- Traditional ASP.NET: Add this to your
Global.asax.cs:protected void Application_Start() { RouteTable.Routes.MapHubs(); } - ASP.NET Core: Add this to
Program.cs:builder.Services.AddSignalR(); // ... app.MapHub<LotteryHub>("/lotteryHub");
Step 4: Update Your Lottery Logic
When the user clicks the draw button, generate the result, show it on the current page, and broadcast it via SignalR:
// Traditional ASP.NET example (MVC Controller) public ActionResult DrawLottery() { // Run your existing lottery logic to get the result string lotteryResult = GenerateRandomResult(); // Show result on current page (return it as JSON for frontend to display) var hubContext = GlobalHost.ConnectionManager.GetHubContext<LotteryHub>(); hubContext.Clients.All.ReceiveLotteryResult(lotteryResult); return Json(new { success = true, result = lotteryResult }); } // ASP.NET Core example (Controller with dependency injection) private readonly IHubContext<LotteryHub> _hubContext; public LotteryController(IHubContext<LotteryHub> hubContext) { _hubContext = hubContext; } public async Task<IActionResult> DrawLottery() { string lotteryResult = GenerateRandomResult(); await _hubContext.Clients.All.SendAsync("ReceiveLotteryResult", lotteryResult); return Json(new { success = true, result = lotteryResult }); }
Step 5: Add Result Listener to the Second Page
On the page with the results table, connect to the SignalR hub and add new results to the table dynamically:
<!-- Include SignalR scripts (adjust path based on your project) --> <script src="/Scripts/jquery.min.js"></script> <script src="/Scripts/jquery.signalR-2.4.2.min.js"></script> <script src="/signalr/hubs"></script> <!-- For traditional ASP.NET --> <!-- For ASP.NET Core: <script src="/_content/Microsoft.AspNetCore.SignalR.Client/signalr.min.js"></script> --> <script> $(function() { // Connect to the hub var lotteryHub = $.connection.lotteryHub; // Traditional // For ASP.NET Core: const connection = new signalR.HubConnectionBuilder().withUrl("/lotteryHub").build(); // Define the method to receive results lotteryHub.client.receiveLotteryResult = function(result) { // Add the result to your table const row = `<tr> <td>${result}</td> <td>${new Date().toLocaleString()}</td> </tr>`; $("#lotteryResultsTable tbody").append(row); }; // Start the connection $.connection.hub.start().done(function() { console.log("Connected to lottery hub"); }); // For ASP.NET Core: connection.start().catch(err => console.error(err.toString())); }); </script> <!-- Your results table --> <table id="lotteryResultsTable"> <thead> <tr> <th>抽奖结果</th> <th>抽奖时间</th> </tr> </thead> <tbody></tbody> </table>
If real-time isn't a strict requirement, you could also store results in a database/Session and have the second page refresh periodically to fetch new entries—but SignalR gives a much smoother user experience.
For desktop apps, you can use event-driven communication to share the lottery result between windows. Here's how to do it in WinForms:
Step 1: Add a Static Event to Your Lottery Form
In the form with the draw button, define a static event that triggers when a result is generated:
public partial class LotteryForm : Form { // Static event to notify other forms of new results public static event Action<string> LotteryResultGenerated; public LotteryForm() { InitializeComponent(); } private void btnDraw_Click(object sender, EventArgs e) { // Run your existing lottery logic string result = GenerateLotteryResult(); // Show result on current form lblCurrentResult.Text = $"抽奖结果:{result}"; // Trigger the event to send the result to other forms LotteryResultGenerated?.Invoke(result); } // Your existing lottery logic method private string GenerateLotteryResult() { // Replace with your actual code var prizes = new List<string> { "一等奖", "二等奖", "三等奖", "谢谢参与" }; var random = new Random(); return prizes[random.Next(prizes.Count)]; } }
Step 2: Subscribe to the Event in Your Results Form
In the form with the results table (DataGridView), subscribe to the event and update the table when a new result comes in:
public partial class ResultsForm : Form { public ResultsForm() { InitializeComponent(); // Subscribe to the lottery result event when the form loads LotteryForm.LotteryResultGenerated += OnLotteryResultGenerated; } private void OnLotteryResultGenerated(string result) { // WinForms requires cross-thread invocation when updating controls from another thread if (dataGridViewResults.InvokeRequired) { dataGridViewResults.Invoke(new Action<string>(OnLotteryResultGenerated), result); return; } // Add the new result to the DataGridView dataGridViewResults.Rows.Add(result, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } private void ResultsForm_FormClosed(object sender, FormClosedEventArgs e) { // Unsubscribe from the event to avoid memory leaks LotteryForm.LotteryResultGenerated -= OnLotteryResultGenerated; } }
For WPF, the approach is similar—you can use events, or if you're using MVVM, a messenger library like MVVM Light's Messenger to send messages between view models.
内容的提问来源于stack exchange,提问作者Ash93

