【问题标题】:How to handle exception outside of page?如何处理页面外的异常?
【发布时间】:2021-05-13 14:26:24
【问题描述】:

我有一个 C# 项目,我正在尝试将其转换为 ASP.NET 和 C#。这是我的第一个 ASP.NET 项目。

我的用户非常喜欢我以前的项目,因为它灵活且易于使用。我正在尝试尽可能多地复制它。

我设计了一个名为 DM_Services.aspx 的页面,其中包含 3 个面板:

  • 面板 1 有一个搜索按钮和几个用于过滤的字段
  • 面板 2 有几个字段可供编辑
  • 面板 3 有一个网格视图。

最终的目标是用户可以输入过滤器,点击搜索在gridview中加载数据。

用户可以单击网格视图中的一行,它将加载面板 2 中的字段以及用于查看和编辑的数据。

我有一个名为 SQLControl.cs 的 C# 文件,我用它来管理数据访问。

我在该页面的 HasException 部分中不断收到错误消息。

如果我使用以下行:

ClientScriptManager.RegisterOnSubmitStatement(Me.GetType(), "ConfirmSubmit", exception);

我收到以下错误:

当前上下文中不存在“我”这个名字

如果我使用:

ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert(exception);", true);

我得到错误:

'Page'是当前上下文中不存在的类型

如果我使用以下行:

ScriptManager.RegisterStartupScript(This, this.GetType(), Guid.NewGuid().ToString("N"), "alert(exception);", true);

我收到此错误:

当前上下文中不存在名称“This”

如果我使用:

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString("N"), "alert(exception);", true);

然后我得到这个错误:

参数 1:无法从“Productivity_ASPWeb.SQLControl”转换为“System.Web.UI.Control”

我很确定我收到了这个错误,因为它位于页面外部的SQLControl.cs 中。

那么我该如何处理异常呢?

    public bool HasException(bool Report = false)
    {
        if (string.IsNullOrEmpty(exception))
            return false;

        if (Report == true) 
            ClientScriptManager.RegisterOnSubmitStatement(Me.GetType(), "ConfirmSubmit", exception);

        ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert(exception);", true);
        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString("N"), "alert(exception);", true);
        ScriptManager.RegisterStartupScript(This, this.GetType(), Guid.NewGuid().ToString("N"), "alert(exception);", true);

        return true;
    }

【问题讨论】:

  • By Me.GetType() 您是否使用 Visual Basic 意义上的 Me(您所在类的当前实例)?如果是这样,Me 的 C# 等效项是 this。你可以说this.GetType() 或简单地说GetType()。您需要做的是获取调用到您的类的页面实例并使用它。该页面是否创建了您的 SQLControl 类的实例?如果是这样,请使用页面实例对其进行初始化并在您的代码中使用该页面实例
  • DM_Services 有以下行: public SQLControl SQL = new SQLControl();
  • 更改您的SQLControl 构造函数以将Page 作为参数。将其私下存储在您的 SQLControl 类中。使用它

标签: c# asp.net exception types


【解决方案1】:

我从 SQLControl.cs 中删除了 scriptManager 并将代码更改为:

        public bool HasException(bool Report = false)
    {
        if (string.IsNullOrEmpty(exception))
            return false;
        else
        return true;
    }

然后我把scriptmanager放到aspx页面中:

    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert(exception);", true);
    }

【讨论】:

    猜你喜欢
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    相关资源
    最近更新 更多