开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜