【发布时间】:2019-04-04 23:53:20
【问题描述】:
我正在尝试使用 jQuery 插入数据,并且之前已经这样做了。但就目前而言,我是在很长一段时间后才这样做的。现在的问题是我正在尝试使用浏览器进行调试,并且可以看到 Ajax 调用实际上没有被调用。所以这是我的场景:我有一个表格数据,每一行都与一个按钮相关联。如果我点击按钮,相关的行数据将被插入到数据库表中(但这里我在调试器中设置了断点来检查是否调用了 web 方法)。所以这就是我尝试过的:
<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>
然后是这里的 C# 部分:
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;
}
【问题讨论】:
-
alert($text) alerts-popup you correct value in the browser on button click?
-
是的,@Hitesh Gaur 确实如此。问题是在 Visual Studio 的调试模式下没有调用该服务 - 似乎错过了一些东西。
-
如果有帮助,您可以在浏览器的开发人员工具的网络选项卡中检查输出吗?并查看您收到的针对特定 ajax 请求的响应。
-
WebMethod不需要static方法吗? -
不,ajax 实际上并没有在网络标签@Hitesh Gaur 中被调用和检查。
标签: c# jquery asp.net webforms