javascript - AJAX Fill Dropdown based on Dropdown Parent -
im wondering what's wrong script, it's not getting values of cities based on country, please see code:
controller: hotel
private actionresult fillcity(int countryid) { var cities = db.cities.where(c => c.country_id == countryid); return json(cities, jsonrequestbehavior.allowget); }
jquery/ajax
<script> function fillcity() { var countryid = $('#country').val(); $.ajax({ url: '@url.action("fillcity")', type: "get", datatype: "json", data: { countryid: countryid }, success: function (cities) { $("#city").html(""); $.each(cities, function (i, city) { $("#city").append( $('<option></option>').val(city.id).html(city.name)); }); } }); } </script>
view
<div class="form-horizontal"> <div class="form-group"> @html.labelfor(model => model.country, htmlattributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @html.dropdownlistfor(m => m.country, new selectlist(viewbag.countrylist, "id", "country_name"), "select country", htmlattributes: new { @class = "form-control", @onchange = "fillcity()" }) @html.validationmessagefor(m => m.country, "", new { @class = "text-danger" }) </div> </div> </div> <div class="form-horizontal"> <div class="form-group"> @html.labelfor(model => model.city, htmlattributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @html.dropdownlistfor(m => m.city, new selectlist(enumerable.empty<selectlistitem>(), "id", "name"), "select city", htmlattributes: new { @class = "form-control" }) @html.validationmessagefor(model => model.city, "", new { @class = "text-danger" }) </div> </div> </div>
you method marked private never hit. change to
public actionresult fillcity(int countryid) { var cities = db.cities.where(c => c.country_id == countryid).select(c => new { id = c.id, name = c.name }; return json(cities, jsonrequestbehavior.allowget); }
side note: if typeof city
contains more id
, name
properties need generate options (it because contains @ least country_id
), should modify query return collection of anonymous objects containing properties need in view
Comments
Post a Comment