我正在学习如何在我的项目中使用类。我一直在研究DataAccessClass.cs并且表现不错(我认为)。 从数据访问中休息一下,我决定尝试在类中创建一个空白。此void将消息作为javascript警报发送给客户端。它运作良好,但必须包含在每个页面上。当我试图使它成为一个类时,我被告知我的类不包含ClientScript的定义。我在原始页面中包含了所有“使用”指令,但无济于事......任何提示或建议都将不胜感激。
原始代码:
//------------------------------------------------------------------------------
//Name: SendErrorMessageToClient
//Abstract: show alert on client side
//------------------------------------------------------------------------------
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
消息会像这样发送到此void:
if (DataAccessClass.OpenSqlConnection(ref Conn, strConn, out strErrorMessage) == false)
{
string strErrorType = "Database Connection Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
或者这个:
catch (Exception excError)
{
string strErrorType = "Unhandled Exception:";
string strErrorMessage = excError.Message;
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
答案 0 :(得分:0)
ClientScript
属性是每个Page
页面继承的ASPX
类的一部分。因此,你不能只在你的课堂内使用它,除非它(即你的班级)有Page
作为基类。
答案 1 :(得分:0)
this.
适用于类中方法中的字段。
答案 2 :(得分:0)
您收到错误,因为'Clientscript'是从System.Web.UI.Page派生的属性,并且通过移动到单独的类文件,您将无法再访问此属性。
您也可以通过传入页面并将代码修改为
来解决此问题protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage, Page page)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
答案 3 :(得分:0)
您需要将页面传递给函数
SendErrorMessageToClient(Page page, string strErrorType, string strErrorMessage)
以便您可以更改
this.ClientScript...
到
page.ClientScript...
原因是ClientScript是Page类
的一部分或者,可能更好,传递ClientScript对象,而不是页面。 所以你的定义看起来像
SendErrorMessageToClient(ClientScript clientScript, string strErrorType, string strErrorMessage) {
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = String.Format("<script type='text/javascript' language='javascript'>alert('{0}\\n\\n{1}');</script>",
strErrorType, strErrorMessage);
clientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
答案 4 :(得分:0)
你为什么要把这个作为一个班级?它不应该是一个类,它没有任何属性或字段,除非你能想到一个。你明白,如果你把它变成一个类,你仍然需要在每一页上初始化它。
你可以把它变成一个静态字符串方法,你仍然需要在每一页上都包含它。
this.ClientScript.RegisterStartupScript(this.GetType(),“ErrorMessage”,strMessageToClient);