How to submit ASP.NET form only when the submit button is pressed and not when the selected index is changed of a dropdownlist with autopostback?

StackOverflow https://stackoverflow.com/questions/21410297

Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

You can use an UpdatePanel with the button as the trigger. You could also just set the AutoPostBack to false as suggested in your comment.

It has been a while since I worked on ASP.NET WebForms...The world has moved on to ASP.NET MVC and Node.js and Ajax. Maybe use an UpdatePanel? From what I remember I think WebForms posts back to get data in two ways and you can check if it is from the submit by checking Page.IsPostBack

http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback(v=vs.110).aspx

I think the other piece of this puzzle is to check the value of the submit button or add a button click handler on the server for the submit...

http://forums.asp.net/t/1795485.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top