• Now Online : 66
  • admin@codemyne.net

In this article we will see how to populate html select or dropdown dynamically using MVC 3 Razor and Jquery.

Take a select and add script as shown below

    <select id="ddlCountry">

 $(document).ready(function () { 
       FillCountries();
 });
function FillCountries()
{
    $.post("Home/GetCountries", null, function (data) {
        if (data) {
               
        $("#ddlCountry").append("<option value=0>Select...</option>");
        $(data).each(function () {
            $("#ddlCountry").append($('<option/>', { value: this.Id }).html(this.Name));
        });
        }
    }, 'json')
    
}

[HttpPost]
public JsonResult GetCountries()
{
    List<Models.Countries> objCnt = new List<Models.Countries>(Models.Countries.GetCountries());  
    return Json(objCnt);
}

Above jquery post calls the action 'GetCountries' in the controller 'Home'. This action returns the JsonResult object, which is assigned to 'select as shown above'.

Model used to get countries list is shown below

public class Countries
{
    public Int64 Id { get; set; }
    public string Name { get; set; }
       
    public static List<Countries> GetCountries()
    {
        return new List<Countries>
        {                          
            new Countries { Id = 1, Name = "India" },
            new Countries { Id = 2, Name = "Pakisthan" },
            new Countries { Id = 3, Name = "SriLanka" },
            new Countries { Id = 4, Name = "Bangladesh" },
            new Countries { Id = 5, Name = "China" },
            new Countries { Id = 6, Name = "Russia" },
            new Countries { Id = 7, Name = "USA" }
        };
    }
}

Comments/Suggestions are invited. Happy coding......!

Comments Post a Comment