ASP.NET Populate a listbox without a postback

岁酱吖の 提交于 2019-12-06 19:16:38

I mocked one up for you really quickly.

<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

<div>


    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
            <br />
            <asp:ListBox ID="ListBox1" runat="server" DataTextField="yourdesiredcolumnamegoeshere"></asp:ListBox>
        </ContentTemplate>
    </asp:UpdatePanel>

</div>

<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
    ConnectionString="Data Source=;Initial Catalog=;User ID=;password=" 
    ProviderName="System.Data.SqlClient" 
    SelectCommand="SELECT [yourdesiredcolumnamegoeshere] FROM [yourtablenamegoeshere]">
</asp:SqlDataSource>
</form>

On the code behind:

protected void LinkButton1_Click(object sender, EventArgs e)
{
    ListBox1.DataSource = SqlDataSource2;
    ListBox1.DataBind();
}

Of course you would change the SqlDataSource to your stored proc, but when you clicked the button, it would populate that list without a postback. Let me know if you need anything else.

-JJ

If you truly don't want a post back then it must be done somehow on the client using javascript or some other method. If you want it to be done with out the appearance of a post back this can be accomplished using a updatepanel.

First of all, if you do not want postback, it get complicated. Is there a reason to avoid postback?

If however, you do not want postback you have 2 options:

  1. Use web methods. On your page create a static method and decorate it with WebMethod attribute.
  2. Another IHttpHandler. Create an implementation of IHttpHandler and override ProcessRequest

For both actions, you will need to use AJAX to query the server (either the web method, or the http handler). You cannot use the MS AJAX because it will cause a partial postback. Use jQuery to do the request.

Note that the UpdatePanel uses MS AJAX and therefore will cause a partial postback.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!