Rectangle 27 0

c Prevent Postback for DropDown for first value in asp.net webform?


<asp:DropDownList ID="ddCategory"
                  CssClass="form-control"
                  AutoPostBack="true"
                  OnSelectedIndexChanged="ddCategory_SelectedIndexChanged"
                  runat="server"
                  DataTextField="Name"
                  DataValueField="ID"
                  onchange="return onCategoryChange();">
</asp:DropDownList>
function onCategoryChange() {
  var value = $("#<%= ddCategory.ClientID %> option:selected").val(); // use the ClientID from the ddCategory dropdown
  if (value == "0") // this is the value for the "Category" entry
    return false; 
  else {
    __doPostBack('<%= ddCategory.ClientID %>', value);
  }
}

P.S.: Note that I used jQuery to select the selected option in the category dropdown field. If you don't have jQuery available, you have to adopt the selected option selection to use plain JavaScript.

Thanks JS approach works. Not sure if why required field validator is not working may be it works when associated with Submit Button. Anyways thanks i will use JavaScript approach as i cant spend any more time on this.

You also have to adopt your DropDownList so that the JavaScript function gets called. Therefore you add a onchange attribute like this:

You need a JavaScript function to make sure no postback happens when the user selects the "Category" entry. This can look like this:

Note