My question is about autopostback in ASP.NET:
I made a dropdownlist with autopostback on true. Depending on which value the dropdownlist is selected, it will generate some HTML, that works perfectly fine.
But when i put the attribute action in the form tag, it will automatically submit the form if i change the index of the dropdown list.
So i need to submit the form only when i press the submit button and it still needs to generate the HTML when i change the dropdownlist, how can i fix this?
Thanks in advance for your help.
A good rule of thumb is to do things on the server side only when it requires data from the server. That means if you're simply displaying different HTML based on what is selected in a drop down list, then make a simple drop down using HTML/JavaScript instead of involving server side technologies. Fewer moving parts is better.
However, if this HTML is dependent on data from the server side, here's some techniques to handle that:
UpdatePanel is the solution which will asynchronously post back to the server without disturbing the rest of the page. The Page_Load function of the page will run with every asynchronous postback, so make sure you plan for that accordingly.
<asp:ScripManager runat="server" />
<asp:UpdatePanel runat="server" ChildrenAsTriggers="True" UpdateMode="Conditional">
<Content>
<asp:DropDownList runat="server" id="MyDDL" AutoPostBack="True" OnSelectedIndexChanged="MyDDL_SelectedIndexChanged" />
</Content>
</asp:UpdatePanel>
However, I find that UpdatePanels introduce more headaches than they're worth. So I personally tend to use jQuery AJAX instead, pulling down HTML from a simple web service. You can find plenty of examples for how to do that online. Here is an example of a changed event handler and here is jQuery AJAX example.