Reputation: 67
I have a button which will execute this when clicked:
protected void Button6_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"myScript", "AnotherFunction();", true);
}
I also have another server side function which is this:
public void Delete()
{
//Delete Code
}
After clicking the button, it will now go to this javascript
function:
Now what i want to do is, call the Delete()
function on the SERVER side .Here is my javascript function what i have tried so far
function (isConfirm)
{
if (isConfirm)
{
//CALL DELETE FUNCTION HERE Delete();
swal("Deleted!", "Your imaginary file has been deleted.", "success");
}
else
{
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
How can i call that server side function? Any idea?
Upvotes: 1
Views: 8069
Reputation: 419
You can achieve this in 2 ways. Ajax/Web Service or triggering button click in JS. Most simplest is to trigger button click. Use following code.
aspx:
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" ClientIDMode="Static" style="display:none;"/>
c#:
protected void Button1_Click(object sender, EventArgs e)
{
Delete();
}
JS:
document.getElementById('Button1').click();
// jquery
$("#Button1").click();
But if you do not want to postback your page then use Ajax. In Ajax simple, you need to add a webpage say data.aspx, in backend class of data.aspx you to will add following c#
Ajax. C#
[WebMethod]
public static int DoSomething(int Id)
{
return 1;
}
And now you can call this from JS:
$.ajax({
url: APP_PAGE_RELATIVE_PATH + "Data.aspx/DoSomething",
data: "{'Id':5}",
type: "POST",
cache: false,
headers: { "cache-control": "no-cache" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Do Something
},
error: function (xhr, status, error) {
//DebugAlert("Error: " + xhr.responseText);
}
});
Upvotes: 1
Reputation: 782
I'd add a ScriptManager to the page and enable PageMethods;
and code in:
In ASPX:
<asp:ScriptManager runat="server" EnablePageMethods="true" />
In Javascript:
<script>
PageMethods.Delete();
</script>
In ASPX.cs:
[System.Web.Services.WebMethod]
public static void Delete()
{
//Delete Code
}
Upvotes: 0