Monday, October 20, 2014

Populate value from other controller using GET Method--Cascading Dropdown

 Cascading Dropdown using Ajax in MVC


// Controller for Get first drop down
public JsonResult GetAll()
        {
            var list = new List<SelectListItem>();
            var news = _context.BusStopTypes.ToList();
            foreach (var item in news)
            {
                list.Add(new SelectListItem() { Value = item.Id, Text = item.Name });
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

-- Ajax Method for 1st Drop Down
function PopulateBusStopTypsId() {
            $.ajax({
                url: '/BusStopType/GetAll/',
                type: 'GET',
                contentType: 'application/json',
                success: function (result) {

                    $('#BusStopTypeId').find('option').remove();
                    $('#BusStopTypeId').append('<option value=""></option>');

                    $.each(result, function (i, v) {
                        $('#BusStopTypeId').append('<option value="' + v.Value + '">' + v.Text + "</option>");
                    });
                },
                complete: function () {
                    $('#BusStopTypeId').select2();
                    PopulateBusStop();
                }

            });
        }



// Get Second drop down based on first drop down Controller
   public JsonResult GetByBusStopType(string id)
        {
            var list = new List<SelectListItem>();
            var busstops = _context.BusStops.Where(x => x.BusStopTypeId == id).ToList();
            foreach (var item in busstops)
            {
                list.Add(new SelectListItem() { Value = item.Id, Text = item.Name });
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

-- Ajax Method for 2nd Drop Down
   function PopulateBusStop() {

            var busStopTypeId = $('#BusStopTypeId').val();

            $.ajax({
                url: '/BusStop/GetByBusStopType/' + busStopTypeId,
                type: 'GET',
                contentType: 'application/json',
                success: function (result) {

                    $('#BusStopId').find('option').remove();
                    $('#BusStopId').append('<option value=""></option>');

                    $.each(result, function (i, v) {
                        $('#BusStopId').append('<option value="' + v.Value + '">' + v.Text + "</option>");
                    });
                },
                complete: function () {
                    Dropdwnvalue();
                    $('#BusStopId').select2();
                }

            });
        }

No comments:

Post a Comment