单击按钮后,文本框中的Ajax值消失

时间:2013-04-08 04:19:17

标签: asp.net jquery

我有一个jquery,它使用ajax和webmethod从数据库中检索值,如下所示

$(document).ready(function() {
        SearchText();
    });
function SearchText() {
   $(".autosuggest").autocomplete({
            source: function(request, response) {
            $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "InsertPage.aspx/GetAutoCompleteData",
                    data: "{'username':'" + document.getElementById('name').value + 
                        "'}",
                    dataType: "json",
                    success: function(data) {
                        response(data.d);
                    },
                    error: function(result) {
                        alert("Error");
                    }
                });
            }
        });
    }
</script>

,网络方法

[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
    List<string> result = new List<string>();
    using (SqlCommand cmd = new SqlCommand("select DISTINCT UserName from student_details 
           where UserName LIKE '%'+@SearchText+'%'", con))

    {
        con.Open();
        cmd.Parameters.AddWithValue("@SearchText", username);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            result.Add(dr["UserName"].ToString());
        }

使用ajax的文本框是

<asp:TemplateField HeaderText="Student Name">
     <ItemTemplate>                    
        <input type="text" id="name" class = "autosuggest" />
   </ItemTemplate>
</asp:TemplateField>

如果我调试程序,此ajax文本框中的值将变为null,文本框中的输出将变为空,因此我无法进一步将值存储在数据库中。

2 个答案:

答案 0 :(得分:0)

很简单,没有controls的{​​{1}}不会将其值回发给服务器。

您需要在该texbox中添加runat="server",然后才能在服务器上获取该值。

runat="server"

如果它不起作用,您可以使用隐藏字段并使用autocompelete事件。
并在回发时设置隐藏字段值。

答案 1 :(得分:0)

您错过了输入中的“姓名”,因此应该

<input type="text" id="username" name="username" />

另外你使用jQuery所以只需得到如下值:

$('#username').val(); //instead of document.getElementById()
相关问题