views:

44

answers:

2

how to pass the strMessage (from codebehind to the script) to get the alert message

i.e if my strmessage from code behind is hi,

then i need

You Have Used already the message : hi

My code...

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

             }
         }
A: 

In your code behind you could define a variable that will contain the message text:

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

And in the markup:

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

You should also be aware that when you use <%= SomeMessage %>, the message won't be encoded and if it contains some special characters such as ' it might break the javascript. This blog post contains a sample function that encodes strings used in javascript.

Darin Dimitrov
but it is not giving me the message to display in alert box
Ranjana
+1  A: 

Depending on at what point you want the alert message to appear, consider using RegisterStartupScript / RegisterClientScriptBlock. Here's a sample (also using the AntiXSS library to javascript-encode the word to mitigate against quotes or any kind of XSS attack).

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);
        }
    }
}
PhilPursglove