User475983607 posted
i want to make a implementation where a user can send a signal to the server trough a linkbuttons click event. however, the page does not have to update. i update it with javascript.
how can i send a method to the server without refreshing/updating/updatepanneling the page/control.
This is an ASP.NET Web Forms application?
Use the browser's
XHR API to send a request using JavaScript. The following example uses
jQuery/AJAX. The client invokes a Web Method but you can send an HTTP request to whatever endpoint you like.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxDemo.aspx.cs" Inherits="WebFormsDemo.AjaxDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</form>
<script>
$("#<%= LinkButton1.ClientID%>").click(function (e) {
e.preventDefault();
var data = {
inputParam: "Hello World"
}
$.ajax({
type: "POST",
url: '/AjaxDemo.aspx/DoSomething',
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
}).done(function (data) {
console.log(data);
});
});
</script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsDemo
{
public partial class AjaxDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string DoSomething(string inputParam)
{
return $"You sent {inputParam}.";
}
}
}