Thursday, May 26, 2011

How to dynamically populate DropDownList from ASP.NET MVC JsonResult using jQuery

The View:

@model TestDropdownList.Models.Person
           

<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.CountryCode, "Country")

    @Html.DropDownListFor(x => x.CountryCode, new List<SelectListItem>() )
}


<script type="text/javascript">
    $(function () {

        $.ajax({ url: '/Home/CountryList/',
            type: 'POST',
            dataType: 'json',
            success: function (data) {

                var options = $('#CountryCode');

                $.each(data, function () {
                    // alert(this.Key + " " + this.Value); // came from .NET Dictionary's Key Value pair
                    options.append($('<option />').val(this.Key).text(this.Value));
                });
            }
        });

        


        $('#CountryCode').change(function () {
            // alert('hello');
            alert($(this).val() + ": " + $('option:selected', $(this)).text());

        });
    });
</script>




The Controller:

[HttpPost]
public JsonResult CountryList()
{            
    // normally, you pass a list obtained from ORM or ADO.NET DataTable or DataReader
    return Json(new Dictionary<string, string>() { { "PH", "Philippines" }, { "CN", "China" }, { "CA", "Canada" }, { "JP", "Japan" } }.ToList());
}


Related to: http://www.ienablemuch.com/2011/05/cascading-dropdownlist-using-aspnet-mvc.html

Search Keywords: json result asp.net mvc html.dropdownlist callback

No comments:

Post a Comment