Hii nauna,
You can't call Web Method from User Control.
Create a Web Service and write the web method inside it, then use the web service to make Ajax call.
Refer below sample.
User Control
HTML
<asp:ListView ID="lvCustomers" runat="server">
<ItemTemplate>
<div id="dvhitem">
<asp:Label ID="lblCustomerId" runat="server" Text='<%#Eval("CustomerId") %>'></asp:Label>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
<asp:Label ID="lblCountry" runat="server" Text='<%#Eval("Country") %>'></asp:Label>
<asp:LinkButton ID="lnkComparisionList" runat="server">Save</asp:LinkButton>
</div>
<hr />
</ItemTemplate>
</asp:ListView>
Namespaces
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
Code
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
this.BindListView();
}
}
private void BindListView()
{
string constring = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
lvCustomers.DataSource = dt;
lvCustomers.DataBind();
}
}
}
}
}
Web Service
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public void Save(string name, string country)
{
string constring = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES(@Name, @Country)", con))
{
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Country", country);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Default
HTML
<uc:WebMethod runat="server" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('[id*=lnkComparisionList]').on('click', function () {
var item = $(this).closest('[id*=dvhitem]');
var obj = {};
obj.name = $(item).find('[id*=lblName]').html();
obj.country = $(item).find('[id*=lblCountry]').html();
$.ajax({
type: "POST",
url: "WebService.asmx/Save",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
return false;
});
});
</script>
Screenshot