My DB consists of Regions, Divisions & States. My application (ASP.NET MVC) application uses entityframework to bind data to DropDown.
- Created Action to bind Regions by default.
- Created Action with RegionId as parameter to retrive Divisions
- [HttpGet]
- public JsonResult GetDivisionsByRegions(string regionID = "")
- {
- try
- {
- List<Division> allDivisions = new List<Division>();
- int ID = 0;
- if (int.TryParse(regionID, out ID))
- {
- using (GeoEntities data = new GeoEntities())
- {
- allDivisions = data.Divisions.Where(div => div.RegionID == ID).OrderBy(div => div.DivisionID).ToList();
- }
- }
- if (Request.IsAjaxRequest())
- {
- return new JsonResult
- {
- Data = allDivisions,
- JsonRequestBehavior = JsonRequestBehavior.AllowGet
- };
- }
- else
- {
- return new JsonResult
- {
- Data = "Invalid Data",
- JsonRequestBehavior = JsonRequestBehavior.AllowGet
- };
- }
- }
- finally
- {
- }
- }
- jQuery AJAX call to GET data from & bind to Dropdown.
- <script type="text/javascript">
- $(document).ready(function () {
- $('#RegionID').change(function () {
- var regionID = parseInt($('#RegionID').val());
- if (!isNaN(regionID)) {
- var ddDivision = $('#DivisionID');
- ddDivision.empty();
- ddDivision.append($("<option></option>").val("").html("Select Division"));
- $.ajax({
- url: "@Url.Action("GetDivisionsByRegions","GetGeoData")",
- type: "GET",
- data: { regionID: regionID },
- dataType: "json",
- success: function (data) {
- $.each(data, function (i, value) {
- ddDivision.append(
- $('<option></option>').val(value.DivisionID).html(value.DivisionName)
- );
- });
- },
- error: function () {
- alert('Sorry!! Error');
- }
-
- });
-
- }
- });
- });
- </script>
- Able to get data from entity.
- Error when bindig to Division drop down
Please help me out..