G Gr
G Gr

Reputation: 6080

Javascript to code behind in c# asp.net

Hi im looking to find out after I do this:

c#

div.Attributes.Add("onclick", "return confirm_delete();");

javascript:

function confirm_delete()
{
  if (confirm("Are you sure you want to delete this comment?")==true)
    return true;
  else
    return false;
}

It pops up with a message box with yes and no if I press yes how can I add a function into my c# how can I call it?

If yes go to c# code behind

and add in confirm_delete 
if yes was clicked
do this 

I need it so when some one clickes yes I can (from code behind in asp.net c#) add in a method to delete from mysql database.

Just dont know how I refrence to the javascript

public static string confirm_delete()
{

    return something (dont know how to)

}

Upvotes: 1

Views: 4938

Answers (4)

Bryan Weaver
Bryan Weaver

Reputation: 4473

How about this add a button with the clientside click event instead of adding it in the code behind. Check to see if the popup returns true. If you return false it should prevent the server side event from firing.

<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/* post back*/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>



protected void btnDelete_Click(object sender, EventArgs e)
{

  //run your serverside code if confirm was pressed.

}

Upvotes: 1

gbs
gbs

Reputation: 7266

Wondering why you are using a div? Can't you use asp.net Button / LinkButton and limiting it's postback based on confirm value? e.g.

<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
    CommandName="Delete" Text="Delete"
    OnClientClick="return confirm('Are you certain you want to delete this 
product?');">
</asp:LinkButton>

Reference.

Upvotes: 0

santosh singh
santosh singh

Reputation: 28652

You may be able to use a PageMethod to call your codebehind function, check out the following link for an example

ASP.NET Ajax PageMethods

Upvotes: 1

3Dave
3Dave

Reputation: 29051

Your JavaScript will need to call a page on your server. This is typically accomplished with AJAX and a web service.

This page on MSDN has a good overview of what's involved.

If you're interested in using jQuery, this page has a simple example.

Upvotes: 1

Related Questions