Learning Learning - 3 months ago 31
ASP.NET (C#) Question

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

I have simple webform with search and other filter.

Search is triggered when user click on the Search Button and filter is trigger based on dropdown change.

CODE

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<asp:TextBox ID="txtSearch" runat="server" placeholder="SEARCH" CssClass="form-control search-text"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" CssClass="btn search-btn" />
</div>


<div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 ">
<asp:DropDownList ID="ddCategory" CssClass="form-control" AutoPostBack="true" OnSelectedIndexChanged="ddCategory_SelectedIndexChanged" runat="server" DataTextField="Name" DataValueField="ID" >
</asp:DropDownList>
<asp:RequiredFieldValidator id="rfvdd" runat="server" ErrorMessage="" ControlToValidate="ddCategory" InitialValue="0" ValidationGroup="ddCategory">
</asp:RequiredFieldValidator>
</div>


CODE BEHIND

String strSql = "SELECT ID, Name FROM Category ORDER BY Name ASC";
DataSet ds = new DataSet();
ds = DataProvider.Connect_Select(strSql);
ddCategory.DataSource = ds;
ddCategory.DataBind();
ddCategory.Items.Insert(0, new ListItem("CATEGORY", "0"));


Using code i as 0 value to Category in
ddCategory
and i dont want to trigger postback when user select Category as an option in
ddCategory
dropdown.

At present when even i select a value postback happens event if it is the first value in the dropdown
Category
with value
0


How can i avoid such postback

Answer

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

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);
  }
}

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

<asp:DropDownList ID="ddCategory"
                  CssClass="form-control"
                  AutoPostBack="true"
                  OnSelectedIndexChanged="ddCategory_SelectedIndexChanged"
                  runat="server"
                  DataTextField="Name"
                  DataValueField="ID"
                  onchange="return onCategoryChange();">
</asp:DropDownList>

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.