按钮单击事件在ASP.NET C#后面的代码中不起作用

时间:2015-02-25 20:57:03

标签: c# asp.net

我的网站上有一个按钮根本不起作用。每当我在代码后面的按钮事件中编写脚本时,我都会收到此错误:

 Server Error in '/website.com' Application.
  Compilation Error
   Description: An error occurred during the compilation of a resource       
   required to service this request. Please review the following specific 
   error details and modify your source code appropriately.

   Compiler Error Message: CS1061: 'ASP.test_aspx' does not contain a 
   definition for 'btnSubmit_Click' and no extension method 
   'btnSubmit_Click' accepting a first argument of type 'ASP.test_aspx' 
   could be found (are you missing a using directive or an assembly 
   reference?)

 Source Error:


  Line 5:  
  Line 6:  
  Line 7:  <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
     OnClick="btnSubmit_Click" />
  Line 8:  
  Line 9:  

背后的代码

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

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

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            lblmsg.Text = "Hello World!";
        }
    }
}

来源:

  <%@ Page Title="" Language="C#" MasterPageFile="~/webMaster.Master"  
  AutoEventWireup="True" CodeBehind="Test.aspx.cs"  
  Inherits="website.Test"  %>

    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" 
     runat="server">
      <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
       OnClick="btnSubmit_Click" CausesValidation="False" />

      <asp:Label ID="lblmsg" runat="server"></asp:Label>  
    </asp:Content>

这是我的Test.aspx.designer.cs代码:

 namespace website {
     public partial class Test {

    /// <summary>
    /// btnSubmit control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind  
        file.
    /// </remarks>
       protected global::System.Web.UI.WebControls.Button btnSubmit;

    /// <summary>
    /// lblmsg control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind 
        file.
    /// </remarks>
    protected global::System.Web.UI.WebControls.Label lblmsg;
   }
 }

更新

我在将CodeBehind =“Test.aspx.cs”更改为CodeFile =“Test.aspx.cs”后解决了这个问题。更多信息CodeFile vs CodeBehind

2 个答案:

答案 0 :(得分:1)

您没有显示所需代码的第3部分,其中事件使用委托初始化,即那种东西。自动创建的代码,我们通常不太关注。请参阅文件InitializeComponent()中的方法Formxxx.Designer.cs

为了简单起见,我建议:只需删除按钮单击事件处理程序,然后单击设计器中的按钮,使用Visual Studio再次创建它。然后正确创建所有必需的代码部分。

答案 1 :(得分:0)

只需从后端删除点击事件protected void btnSubmit_Click(object sender, EventArgs e),然后从aspx中构建OnClick="btnSubmit_Click"构建解决方案,然后再次定义click事件并绑定它。

删除自动生成的点击事件时会发生这种情况。

相关问题