Return City ID and JSON Name MVC4

I have a function in the MVC controller that allows me to get city identifiers by country. And I have a java script function that calls this method in the controller

[HttpPost]
public ActionResult GetcitiesBycountry(string selectedValue)
{
List<string> cityList = new List<string>();
if (selectedValue != null && selectedValue.Length > 0)
{
using (InstructoroEntities dataContext = new InstructoroEntities())
{
int ID = int.Parse(selectedValue);
List<string> getcities = dataContext.Cities.Where(query => query.CountryID 
==ID).Select(q => q.CityName).ToList();
cityList = getcities;
}
}
return Json(new { CityList = cityList });
}


<script type="text/javascript">
$("#CountryID").change(function () {
var selectedValue = $(this).val();
$.ajax({
url: '@Url.Action("GetcitiesBycountry", "Registration")',
type: 'POST',
data: { "selectedValue": selectedValue },
dataType: 'json',
success: function (response) {
var items = "";
$.each(response.CityList, function (i, item) {
items += "<option value=\"" + item + "\">" + item + "</option>";
});
$("#CityName").html(items);
},
error: function (error) {
}

});
});
</script>

I just want to get a city identifier and a name instead of a name with best wishes.

+4
source share
1 answer

Change as shown below.

C #: use

var getcities = dataContext.Cities.Where(query => query.CountryID ==ID)
.Select(q => new{q.CityName, q.CityID}).ToList(); 
    }
}   
return Json(getcities);

Instead

List<string> getcities = dataContext.Cities.Where(query => query.CountryID 
==ID).Select(q => q.CityName).ToList();
cityList = getcities;
    }
}
return Json(new { CityList = cityList });

JQuery: use

$.each(response, function (i, item) {
    items += "<option value=\"" + item.CityID + "\">" + item.CityName + "</option>";
});

Instead

$.each(response.CityList, function (i, item) {
    items += "<option value=\"" + item + "\">" + item + "</option>";
}); 
+5
source

All Articles