Codebehind confirm box

When a users click the save button on the page the

protected void ibSaveRecord_Click(object sender, ImageClickEventArgs e)

Method is fired. What I wna to do is ccheck that the user has made any changes, if they havent pop up an cofirm box which exits the method if they cancel and redirects to another page if they confirm (bypassing the rest of the script.

I have my If statement which checks if anything has changed - how do i do the rest?

cheers

Are you using JavaScript or C# to check if they have made any changes?

You can dynamically tie a Javascript function to a button control like this:

JAVASCRIPT


function showHelloWorld() {
    alert('Hello World');
}

ASP.NET


private void Page_Load(object sender, System.EventArgs e) {
    myButton.Attributes.Add("onclick","showHelloWorld()");
}

I use my code behind to check if a value has changed by comparing to a hidden value set on page first load:


protected void ibSave_Click(object sender, ImageClickEventArgs e)
{
	if (cb1.Checked == bool.Parse(hf1.Value) &&
		cb2.Checked == bool.Parse(hf2.Value))
	{
		//show alert box and react to response
		//if true exit out of code block, else continue
	}
......

Maybe this would work…

Add this to your page:


<script type="javascript">
   <asp:Literal ID="ltlJSConfirm" runat="server"></asp:Literal>
</script>

Then in your code behind add the javascript code to the text property of ltlJSConfirm after you have determined the user should be alerted.


ltlJSConfirm.Text == "alert('Are you sure?')"

I think that will work, although it hasn’t been tested.

No this won’t work - ltlJSConfirm does not exist to VS! Unless you mean:

Response.Write("ltlJSConfirm.Text == \\"alert('Are you sure?')\\"");

?

When you add this to your page


<script type="javascript">
   <asp:Literal ID="ltlJSConfirm" runat="server"></asp:Literal>
</script>

Visual Studio will have an issue with it in the code highlighting, but when the page actually runs on the server - it works. I have used that method in the past.

I imagine it has to do with a control being placed in a script tag that isn’t set to runat the server, but I have used that in the past.

Or, for a way that VS won’t complain about…just put the Literal control in your HTML page (not surrounded by the javascript tags) and in your codebehind use:

ltlJSConfirm.Text == “<script type=”“text/javascript”“>alert(‘Are you sure?’)</script>”

My bad it is the == throwing it (i’m using c#!). Anyway, this set the alert text but the alert is not thrown - am i missing something?

Not sure. If you view the source of the page, does the code look correct to trigger the alert?

Do it without javascript first. They click the button you check it and if necessary redirect to a page that asks them if they are sure etc.

Later after reading up on ajax you can layer your script on top of this to make an ajax call to your logic in the code behind and avoid the need to redirect and it will work with script on or off.