ASP.NET Populate a listbox without a postback

自闭症网瘾萝莉.ら 提交于 2019-12-08 07:44:44

问题


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


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6333961/asp-net-populate-a-listbox-without-a-postback

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