我正在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时: data:'{comtext:“'+ $(”#&lt;%= txtComment.ClientID%&gt;“)[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;
}
请帮助
答案 0 :(得分:0)
$("#MyRepeater").on("click", ".MyButton", function() {
var textBoxValue = $(this).closest("tr").find(".MyTextBox").val(); //$("#MyTextBox").val();
$.ajax({
type: "POST",
url: "index.aspx/insertComment",
data: '{comtext: "' + textBoxValue + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("ok");
//$('#txtComment').val("");
}
});
})
&#13;
[WebMethod]
public static string insertComment(string MyTextboxValue)
{
// 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");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Comment (comtext) values ('" + MyTextboxValue + "')", con);
try
{
cmd.ExecuteNonQuery();
return "Success";
}
catch (Exception ex)
{
return ex.Message;
}
finally {
con.Close();
}
}
答案 1 :(得分:0)
这条线对我有用..
var textBoxValue = $(this).parent("div").siblings('div').children('.txtComment').val();