2010-04-17 71 views
0

如何通过strMessage(从代码隐藏到脚本)来获取警报消息如何通过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); 

      } 
     } 
+1

@Ranjana:我不知道什么是背后张贴的没有任何合理的格式问题的心态。有一个格式化的帮助,有一个所见即所得的预览窗口,这里的其他问题看起来不格式化将无法正常工作。所以......你不再是一个完全*新的用户。现在是时候让你的问题格式正确了。 – Tomalak 2010-04-17 09:21:34

回答

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); 
     } 
    } 
} 
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中使用的字符串进行编码。

+0

但它没有给我提示框中显示的消息 – Innova 2010-04-17 10:49:17

0

建立与字符串生成器或任何你喜欢你的信息,并将其传递给下面的空隙

//------------------------------------------------------------------------------ 
//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); 

}