如何传递strMessage(从代码后面到脚本)来获取警报消息

时间:2010-04-17 09:15:50

标签: c# asp.net javascript

如何传递strMessage(从代码隐藏到脚本)以获取警报消息

即 如果我的代码背后的strmessage是嗨,

然后我需要

您已使用过消息:嗨

我的代码......

<script type="text/javascript">
     var strFileName;

    function alertShowMessage() {
    alert("You Have Used already the message :"+ <%=strFileName %>+ ");
    }
</script>


datatable dtChkFile =new datatable();
dtChkFile = objutility.GetData("ChkFileName_SMSSent", new object[] {"rahul"}).Tables[0];
         if (dtChkFile.Rows.Count > 0)
         {
             for (int i = 0; i < dtChkFile.Rows.Count; i++)
             {
                  strMessage= dtChkFile.Rows[i]["Message"].To);

             }
         }

3 个答案:

答案 0 :(得分:1)

根据您希望显示提醒消息的位置,请考虑使用RegisterStartupScript / RegisterClientScriptBlock。这是一个示例(也使用AntiXSS library来对单词进行javascript编码以减轻引号或任何类型的XSS攻击。

using Microsoft.Security.Application;

namespace RegisterClientScriptBlock
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String alertScript;
            String inputWord;
            String encodedWord;

            encodedWord = AntiXss.JavaScriptEncode(inputWord);

            alertScript = "function alertShowMessage() {";

            if (checkIfWordHasBeenUsed(inputWord) == true)
            {
                alertScript = alertScript + "alert('You have already used the message:" + encodedWord + "');}";
            }
            else
            {
                alertScript = alertScript + "alert('You have not used the message:" + encodedWord + "');}";
            }

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertShowMessage", alertScript, true);
        }
    }
}

答案 1 :(得分:0)

在您的代码中,您可以定义一个包含消息文本的变量:

public partial class _Default : System.Web.UI.Page
{
    public string SomeMessage = "Hello World";
}

在标记中:

<script type="text/javascript">
function alertShowMessage() {
    alert('You Have Used already the message : <%= SomeMessage %>');
}
</script>

您还应该注意,当您使用<%= SomeMessage %>时,邮件将不会被编码,如果它包含一些特殊字符,例如',则可能会破坏javascript。 This blog post包含一个示例函数,用于对javascript中使用的字符串进行编码。

答案 2 :(得分:0)

使用字符串构建器或您喜欢的任何方法构建消息,并将其传递给以下void

//------------------------------------------------------------------------------
//Name: SendMessageToClient
//Abstract: Send a message to the client side.
//------------------------------------------------------------------------------
protected void SendMessageToClient(string strMessage)
{
string strMessageToClient = "";

//Allow single quotes on client-side in JavaScript
strMessage = strMessage.Replace("'", "\\'");

strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strMessage + "' );</script>";

this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);

}