如何在 jquery ajax 中访问中继器文本框



我正在 Asp.net Webforms ajax jquery中制作一个实时评论系统。我有一个中继器,其中我有一个文本框和一个按钮...我想简单地通过 ajax jquery 插入,但 jquery ajax 没有找到在中继器控件中声明的文本框......

脚本:

$(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...但是当我像这样尝试在中继器之外使用文本框时:data: '{comtext: "' + $("#<%=txtComment.ClientID%>")[0].value + '" }'那么它对我有用,但找不到中继器中的文本框

代码隐藏:

[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;
    }

请帮忙

 $("#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("");
     }
   });
 })

[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();
    } 
}

这行对我有用。

var textBoxValue = $(this).parent("div").siblings('div').children('.txtComment').val();

最新更新