Tuesday, 13 December 2011

Binding the Data To a Asp:dropdownlist using ajax in Entity FrameWork and On button click Accessing the Value in Code Behind.

OR

Accessing a HTML Control in C#.


Aspx file:

<table width="95%" border="0" class="planYourStay" cellpadding="0" cellspacing="0">
<tr>
<td width="50%" height="30" valign="top">
<span class="label16">State</span><br />
<asp:DropDownList ID="drpState" runat="server">
<asp:ListItem Value="0">--Select--</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvdrpState" runat="server" ControlToValidate="drpState"
 Text="*" CssClass="errormsg" ValidationGroup="step1" InitialValue="0">
</asp:RequiredFieldValidator> 
</td>
<td width="45%" valign="top">
<span class="label16">City</span><br />
<asp:DropDownList ID="drpCity" runat="server">
<asp:ListItem Value="0" runat="server">--Select--</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfcdrpCity"   runat="server" ControlToValidate="drpCity"
Text="*" CssClass="errormsg" ValidationGroup="step1" InitialValue="0">
</asp:RequiredFieldValidator> 
</td>
</tr>
</table>
 <asp:ImageButton ID="imgbtnStep2" runat="server" ImageUrl="images/step2-but.gif"
OnClick="imgbtnStep2_Click"  ValidationGroup="step1" /> 
 
Jquery File: 
$(document).ready(function () {
          $("#<%=drpState.ClientID %>").change(function () {
              var $cities = $('#<%=drpCity.ClientID %>');
             $.ajax({
                 type: "POST",
                 url: "Default.aspx/GetCities",
                 contentType: "application/json; charset=utf-8",
                 data: '{stateId: ' + $('#<%=drpState.ClientID%>').val() + '}',
                 dataType: "json",
                 success: function (cities) {
                     $.each(JSON.parse(cities.d), function (i, city) {
                         $cities.append('<option value="' + city.CityID + '">' + 
city.Name + '</option>');
                     });
                 },
                 error: function () {
                     alert('Failed to retrieve states.');
                 }
             });
         });
     }); 
C# web service(Ajax Method): 
[System.Web.Services.WebMethod]
       public static string GetCities(string stateId)
        {
            if (Convert.ToInt32(stateId) == 0)
            {
                return null;
            }
           var result = Common.GetCities().Where(res => res.StateID == 
                                       Convert.ToInt32(stateId)).ToArray();
           var City2 = new {CityID=0, Name=string.Empty};
           var cityList = new[] {City2}.ToList();
            foreach (var city in result)
            {
                cityList.Add(new{CityID=city.CityId,Name=city.City1});
            }
            cityList.RemoveAt(0);
            return new JavaScriptSerializer().Serialize(cityList);
        }
 
Image Button click event: 
 protected void imgbtnStep2_Click(object sender, ImageClickEventArgs e)
        {
            string selectedValue = Request.Params.Get(drpCity.UniqueID); 
// OR string selectedValue = Request.Form.Get(drpCity.UniqueID); 
// Request.Form and request.Params are used for accessing the 
// client side controls in Code behind
            TempData tempData = new TempData()
                                    {
                                        City = selectedValue,
                                      State=drpState.SelectedValue,
                                       Week=drpWeekInterval.SelectedValue,
                                       Package=GetPackage(),
                                       CheckInDate = txtCheckin.Text.Trim()
                                    };
            Session["TempData"] = tempData;
            Response.Redirect("~/Registration.aspx");
        }
 
 

No comments:

Post a Comment