简体   繁体   中英

ASP.NET Populate a listbox without a postback

I have a simple aspx page with a textbox, linkbutton and listbox.

The listbox is to be populated with values from a stored procedure in a SQL database.

What I'd like to do, somehow, is to populate the listbox with those variables when the user clicks the linkbutton. Ideally, I'd like to do this WITHOUT a postback.

Is there any way this can be accomplished?

Thanks,

Jason

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM