使用ajax分配文本框值 - 页面仍然刷新,分配的值已消失

时间:2015-01-03 21:26:43

标签: javascript asp.net ajax json asp.net-ajax

我正在尝试使用AJAX而不是C#来填充我的网页的一部分,因为不应该为此操作刷新网页。我需要做的就是运行SELECT查询并从SQL DB获取当前客户端并填写相关表单而不刷新页面。我设法获取相关客户端并更改相关文本框,但页面仍然刷新,所有文本框再次变为空!

我的代码如下:

    <asp:Panel ID="pnlClientSummaryDetails" runat="server" Width="360px" Visible="True">
       <asp:TextBox runat="server" ID="txtDateOpened"></asp:TextBox>
       <!--other text boxes -->
    </asp:Panel>

    <asp:Button ID="bnSelectClient" runat="server" CssClass="auto-style7" Text="Select Client" ToolTip="Click the view client button to view selected clients information" Width="282px" OnClientClick="BindClientSummaryForm()" />

    function BindClientSummaryForm() {
            $.ajax({
                type: "POST",
                url: "Clients.aspx/GetClientSummaryData",
                contentType: "application/json;charset=utf-8",
                data: {},
                dataType: "json",
                success: function(data) {
                    document.getElementById('<%= txtDateOpened.ClientID %>').value = data.d.DateFileOpened;
                  // other textboxes will be filled like that.
                },
                error: function (result) {
                    alert("Error occured while filling ClientSummary part.");
                }
            });
        }

[WebMethod] 
        public static MyClient GetClientSummaryData() //GetData function
        {
            //FillClientSummaryGridView();
            int intClientID = 0; 
            Int32.TryParse(clientID, out intClientID);
            MyClient client = new MyClient();
            string sQuery = "SELECT ClientID,FirstName,DateFileOpened FROM dbo.Client where ClientID = " + intClientID;
            String sConnectionString = ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString;
            SqlConnection con = new SqlConnection(sConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand(sQuery, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dtGetData = new DataTable();
            da.Fill(dtGetData);

            foreach(DataRow dtRow in dtGetData.Rows)
            {
                client.Firstname = dtRow.ItemArray[1].ToString();
                client.DateFileOpened = dtRow.ItemArray[2].ToString();            
            }
            return client;
        }

我该怎么做朋友?我必须阻止页面刷新并保留由ajax的成功部分分配的文本框值。谢谢!

1 个答案:

答案 0 :(得分:1)

请尝试在ajax调用后向您的BindClientSummaryForm函数添加return false,同时修改调用函数的方式:OnClientClick =“return BindClientSummaryForm();”

如果这不起作用,请尝试从函数中删除return false并改为使用它:OnClientClick =“BindClientSummaryForm(); return false;”