I've working with my ajax call in my MVC project and I've decided to implement json call here is my example:
View:
<
select id="cmbContinent">
<option value="---" selected="selected">Choose Continent...</option>
<option value="eur">Europe</option>
<option value="ame">America</option>
<option value="asi">Asia</option>
<option value="afr">Africa</option>
</select>
<select id="cmbCountries"></select>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
//****Ajax Example****
$("#cmbContinente").change(function() {
fillCombo("cmbCountries", $("#cmbContinent").val());
});
});
//****Ajax Example****
function fillCombo(updateId, value) {
$.getJSON("<%= Url.Action("CountriesPerContinent") %>" + "/" + value,
function(data) {
$("#"+updateId).empty();
$.each(data, function(i, item) { $("#"+updateId).append("<option id='" + item.IDCountries +"'>" + item.Name + "</option>");
});
});
}
}
</script>
Controller:
[ActionName("CountriesPerContinent")]public ActionResult GetCountriesPerContinent(string id)
{
var Count = new CountriesModel().GetCountriesPerContinent(id);
return new JsonResult() { Data = Count };
}
Model:
public class Country
{
public string Continente { get; set; }
public string Nombre { get; set; }
public string IDPaises { get; set; }
}
public class CountriesModel
{
private List<Pais> paises;public PaisesModel()
{
this.paises = new List<Country>();
this.paises.Add(new Country()
{
Continente = "eur", IDPaises = "es",
Nombre = "Espaa"
});
// return
}
public IEnumerable<Country> GetCountriesPerContinent(string continent)
{
return this.Count.FindAll(x => x.Continent == continent);
}
}
Hope That Help guys!!