【发布时间】:2016-04-25 19:06:03
【问题描述】:
我正在 Asp.net Webforms ajax jquery 中制作实时评论系统.... 我有一个Repeater,我有一个TextBox和一个Button...我只想通过ajax jquery插入,但是jquery ajax没有找到在Repeater控件中声明的TextBox...
脚本:
$(document).ready(function () {
$('#btnComment').click(function () {
$.ajax({
type: "POST",
url: "index.aspx/insertComment",
data: '{comtext: "' +txtComment.value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("ok");
//$('#txtComment').val("");
}
});
});
});
</script>
当我调试脚本时,数据有问题....txtComment.value... 但是当我尝试像这样在Repeater之外的TextBox时: 数据:'{comtext: "' + $("#")[0].value + '" }' 然后它对我有用,但在Repeater中找不到TextBox
代码背后:
[WebMethod]
public static string insertComment(string comtext)
{
//Button btnComment = sender as Button;
//RepeaterItem item = btnComment.NamingContainer as RepeaterItem;
//TextBox txtComment = item.FindControl("txtComment") as TextBox;
//lblMsg.Text = txtComment.Text;
SqlConnection con = new SqlConnection("data source=RIO;initial catalog=SocialNetworkSite;integrated security=true");
SqlCommand cmd = new SqlCommand("insert into Comment (comtext) values ('" + comtext + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return comtext;
}
请帮忙
【问题讨论】:
-
你做错了。您的 WebMethod 不能也不应该从页面访问控件。为了回答为什么您的 jQuery 找不到
#txtComment,您需要展示您是如何创建它的。很可能是客户端的 ID 与您的预期不符。 -
这是我想在脚本中访问但不能访问的文本框...
我对 jquery 不太了解,但我认为可以使用遍历来完成.....我试过这个... var textBoxValue = $(this) .closest("div").find("#txtComment").val(); data: '{comtext: "' + textBoxValue + '"}' 但它显示.....textBoxValue=undefined........请帮帮我 -
就像我说的,在客户端查看您的文本框的 ID。您在 ASPX 标记中输入的内容不一定是您在结果页面中获得的内容。
标签: jquery asp.net ajax repeater webmethod