I am trying to insert data using jQuery
and have done that earlier. But for the time being, I am doing this after a long time. Now the issue is I am trying to do debugging with browser and can see that the Ajax call actually doesn't get called. So here is my scenario: I've a table data and every row is associated with a button. If I click on the button, the associated row data will be inserted into database table (But here I put break-point in the debugger to check if the web method is called). So this is what I've tried:
<title>Tutorial - Sample App</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblPersons" runat="server"></asp:Label>
</div>
</form>
<script>
$(".use-address").click(function () {
var $row = $(this).closest("tr"); //Get the row
var $text = $row.find(".val").text(); //Get the text or value
alert($text);
debugger;
var persons = new Array();
var person = {};
person.name = $row.find(".val").text();
persons.push(person);
//The Ajax call here
$.ajax({
type: "POST",
url: "/SampleWebForm.aspx/InsertPersons", //This isn't called actually and keeping the code in the same page - SampleWebForm.aspx
data: JSON.stringify(persons),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data + " record(s) inserted.");
}
});
});
</script>
Then the C# section here:
protected void Page_Load(object sender, EventArgs e)
{
lblPersons.Text = Concatenate();
}
public class Person
{
public string name { get; set; }
public string age { get; set; }
}
public List<Person> GetPersons()
{
List<Person> lst = new List<Person>
{
new Person { name = "John", age = "20" },
new Person { name = "Jack", age = "30" }
};
return lst;
}
public string Concatenate()
{
string data = "";
data += "<table id = 'tblPersons'" +
"<thead>" +
"<tr class='ui-widget-header'>" +
"<th>Name</th>" +
"<th>Age</th>" +
"</tr>" +
"</thead>" +
"<tbody>" +
"";
foreach (var item in GetPersons())
{
data += "<tr><td class='val'><span>" + item.name + "</span></td>" +
"<td>" + item.age + "</td><br/>" +
"<td><button type = 'button' id = 'btnSave'>Click Here</button><td><tr>" +
"</td>";
}
data += "" +
"</tbody>" +
"</table>";
return data;
}
[WebMethod]
public string InsertPersons(Person persons) //This is the method that's supposed to be hit while debugging but doesn't
{
string name = "";
name = persons.name;
return name;
}