c# - 从 aspx 页面上的按钮调用类

标签 c# asp.net class onclick

我的页面似乎刚刚刷新。我无法调用 LottoTest() 类 onclick。

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Draw.aspx.cs" Inherits="Lotto.Draw" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Welcome to the Lotto draw</h1>
        <asp:Button ID="button1" runat="server" Text="DRAW" OnClientClick="LottoTest()" />
    </div>
    </form>
</body>
</html>

Draw.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Lotto
{
    public partial class Draw : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }


        public void LottoTest()
        {
            Dictionary<int, int> numbers = new Dictionary<int, int>();
            Random generator = new Random();
            while (numbers.Count < 6)
            {
                numbers[generator.Next(1, 49)] = 1;
            }

            string[] lotto = numbers.Keys.OrderBy(n => n).Select(s => s.ToString()).ToArray();

            foreach (String _str in lotto)
            {
                Response.Write(_str);
                Response.Write("<br/>");
            }
        }
    }
}

最佳答案

问题是您正在发出客户请求。将 OnClientClick 更改为 OnClick(不带括号)。

然后将您的方法签名更改为: public void LottoTest(object sender, EventArgs e) 而不是 public void LottoTest()

关于c# - 从 aspx 页面上的按钮调用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17251221/

相关文章:

JavaScript OR 运算符

c# - 登录 - 仅允许 3 次尝试

c# - 是否可以将 TextBlock 的文本绑定(bind)到应用程序 AssemblyVersion?

c# - LINQ,处理模型中的 Null

c# - ASP.NET MVC 如何在不重写 URL 的情况下处理 Application_Error 的 404 错误

PHP 试图在类中创建动态变量

c# - 如何使用带有复选框和下拉菜单的自动回发?

c# - 空引用文字控制

php - 你能举例说明如何使用 PHP __method__ 吗?

c++ - 循环依赖与可以相互初始化的类