在c#中使用Json Data for Bind Gridview

时间:2012-06-04 10:45:09

标签: c# json

我使用Json绑定Gridview。我在页面中添加了一个文本框,搜索按钮和一个gridview。当页面加载时,所有数据都将在Gridview中绑定。在文本框中输入文本后单击搜索按钮然后搜索结果将显示但它只是附加搜索结果数据与所有数据。我想只是绑定搜索结果数据。

我的代码是

.aspx Page

 <table>
        <tr>
            <td>
                <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
            </td>
            <td>
                <asp:Button ID="btnSearch" runat="server" Text="Search" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:GridView ID="gvDetails" runat="server">
                    <HeaderStyle BackColor="#DC5807" Font-Bold="true" ForeColor="White" />
                </asp:GridView>
            </td>
        </tr>
    </table>

现在脚本就像这样

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {

        //    function () {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Gridview.aspx/BindDatatable",
            async: true,
            cache: false,
            data: "{}",
            dataType: "json",
            success: function (data) {
                for (var i = 0; i < data.d.length; i++) {
                    $("#gvDetails").append("<tr><td>" + data.d[i].OfficeName + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td></tr>");

                }
            },
            error: function (result) {
                alert("Error");
            }
        });

        $('#btnSearch').click
                            (
                                function () {

                                    var searchtext = $("#txtSearch").val();

                                    alert(searchtext);
                                    $.ajax(
                                                {
                                                    type: "POST",
                                                    url: "Gridview.aspx/BindSearchDatatable",
                                                    //data: "{officename : '"+searchtext+"'}",
                                                    data: JSON.stringify({ officename: searchtext }),
                                                    contentType: "application/json; charset=utf-8",
                                                    dataType: "json",
                                                    async: true,
                                                    cache: false,
                                                    success: function (data) {


                                                        for (var i = 0; i < data.d.length; i++) {

                                                            $("#gvDetails").append("<tr><td>" + data.d[i].OfficeName + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td></tr>");
                                                        }
                                                    },
                                                    error: function (x, e) {
                                                        alert("The call to the server side failed. " + x.responseText);
                                                    }
                                                }
                                            );
                                    return false;
                                }
                            );


        // }
    });

</script>

现在.aspx.cs页码

public partial class Gridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindColumnToGridview();
        }
    }

    private void BindColumnToGridview()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("OfficeName");
        dt.Columns.Add("City");
        dt.Columns.Add("Country");
        dt.Rows.Add();
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
        gvDetails.Rows[0].Visible = false;
    }

    [WebMethod]
    public  static OfficeDetails[] BindDatatable()
    {
        DataTable dt = new DataTable();
        List<OfficeDetails> details = new List<OfficeDetails>();

        using (SqlConnection con = new SqlConnection(@"Data Source=kartikpatel\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("select  OfficeName,City,Country from Office", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach (DataRow dtrow in dt.Rows)
                {
                    OfficeDetails Office = new OfficeDetails();
                    Office.OfficeName = dtrow["OfficeName"].ToString();
                    Office.City = dtrow["City"].ToString();
                    Office.Country = dtrow["Country"].ToString();
                    details.Add(Office);
                }
            }
        }
        return details.ToArray();

    }
    [WebMethod]
    public static OfficeDetails[] BindSearchDatatable(string officename)
    {

        DataTable dt = new DataTable();
        List<OfficeDetails> details = new List<OfficeDetails>();

        using (SqlConnection con = new SqlConnection(@"Data Source=kartikpatel\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("select  OfficeName,City,Country from Office where OfficeName like '%" + officename + "%'", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach (DataRow dtrow in dt.Rows)
                {
                    OfficeDetails Office = new OfficeDetails();
                    Office.OfficeName = dtrow["OfficeName"].ToString();
                    Office.City = dtrow["City"].ToString();
                    Office.Country = dtrow["Country"].ToString();
                    details.Add(Office);
                }
            }
        }
        return details.ToArray();
    }
    public class OfficeDetails
    {
        public string OfficeName { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }



}

如果你看到我使用追加这就是为什么搜索结果附加了所有数据。但我只想搜索结果数据当我点击搜索按钮。我搜索谷歌但我没有得到任何东西..请帮助我< / p>

1 个答案:

答案 0 :(得分:1)

正如我从您的代码中看到的那样,您正在使用GridView作为占位符。 我建议做以下

<table>
    <tr>
        <td>
            <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
        </td>
        <td>
            <asp:Button ID="btnSearch" runat="server" Text="Search" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <table>
              <thead>
                  <tr>
                    <td>OfficeName</td>
                  <tr>
                  <tr>
                    <td>City</td>
                  <tr>
                  <tr>
                    <td>Country</td>
                  <tr>
              </thead>
              <tbody>
                  <div id="gvDetails"></div>
              </tbody>
            </table>
        </td>
    </tr>
</table>


<script>
$('#btnSearch').click
                        (
                            function () {

                                var searchtext = $("#txtSearch").val();

                                alert(searchtext);
                                $.ajax(
                                            {
                                                type: "POST",
                                                url: "Gridview.aspx/BindSearchDatatable",
                                                //data: "{officename : '"+searchtext+"'}",
                                                data: JSON.stringify({ officename: searchtext }),
                                                contentType: "application/json; charset=utf-8",
                                                dataType: "json",
                                                async: true,
                                                cache: false,
                                                success: function (data) {

                                                    $("#gvDetails").empty();
                                                    for (var i = 0; i < data.d.length; i++) {

                                                        $("#gvDetails").append("<tr><td>" + data.d[i].OfficeName + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td></tr>");
                                                    }
                                                },
                                                error: function (x, e) {
                                                    alert("The call to the server side failed. " + x.responseText);
                                                }
                                            }
                                        );
                                return false;
                            }
                        );
</script

通过这种方式,标题将始终可见