Thursday, January 9, 2014

Bind dropdownlist with data from json using MVC razor

Controller:

 [HttpPost]
        public JsonResult GetStateList()
        {
            var list = new List<System.Web.UI.WebControls.ListItem>() {
            new System.Web.UI.WebControls.ListItem() { Value = "1", Text = "bhopal" },
            new System.Web.UI.WebControls.ListItem() { Value = "2", Text = "Indore" },
            new System.Web.UI.WebControls.ListItem() { Value = "3", Text = "Jablpur" }
         };
            return Json(list);
        }



View:

        $.ajax({
            type: "POST",
            url: "ControllerName/GetStateList",
           contentType: "json",
           dataType: "json",
           success: function (data) {
              var ddlCountrylist=$('#Claims1');//Dropdown List Id
               var items = data;             
               $(items).each(function (index, optionText) {
                                                      $('<option value=' + optionText.Value + '>' + optionText.Text + '</option>').appendTo(ddlCountrylist);
               });              
                           },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });

No comments:

Post a Comment