Monday, 6 June 2011

Call a Page Method Using Drop Down List and JavaScript

Purpose:

When an item is selected from the drop down list, a method on the server should be called. AutoPostBack = True can’t be used as posting back the whole page is not required.

image

Page Source:

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var selector = ".ddlCountries";
$(selector ).change(function () {
PageMethods.OnSelectedIndexChanged($(selector).val());
});
});
script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
</asp:ScriptManager>

<asp:DropDownList CssClass="ddlCountries" ID="ddlCountries" runat="server" Width="100px">
</asp:DropDownList>
</asp:Content>

Page Code Behind:

   protected void Page_Load(object sender, EventArgs e)
{
BindDummyData();
}

private void BindDummyData()
{
var countries = new [] {new { Name = "UK", ID = "1" },
new { Name = "USA", ID = "2" }
};

foreach (var country in countries)
{
this.ddlCountries.Items.Add(new ListItem(country.Name, country.ID));
}
}

[WebMethod]
public static void OnSelectedIndexChanged(string selectedValue)
{
// process
}

No comments: