Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Json call in MVC

0.00/5 (No votes)
24 Jun 2011 1  
I've working with my ajax call in my MVC project and I've decided to implement json call here is my example: View:  

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

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!!
 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here