Jquery – Bind Json Result to DropDownlist in MVC4

asp.net-mvcasp.net-mvc-4html.dropdownlistforjqueryjson

I am trying to implement a cascading dropdownlist in mvc4. I used dictionary values for the 1st dropdownlist and binded xml values for 2nd dropdownlist. Based on the selection of country(1st DDL),states has to be loaded(2nd DDL).How to bind the jsonresult to the 2nd dropdownlist using jQuery. The JsonResult returns well in the firebug. What is the mistake in my script. Any suggestions will be greatly helpful.

Here is my code.
View

@using (Html.BeginForm("Details", "WPWebGridCart", new { userID = Request.QueryString["UserID"], partnerid = Request.QueryString["Partnerid"] }, FormMethod.Post))
 {
  if (Model.Count() == 0)
  {    
         @Html.DisplayNameFor(model => model.Country)
     @{
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("USA", "USA");
            dictionary.Add("UK", "UnitedKingdom");
            dictionary.Add("India", "India");
            SelectList list = new SelectList(dictionary, "value", "key", "India");
         }
         @Html.DropDownList("Country", list, "(Select Country)", new { @class = "TextBoxBorder" })
     @Html.DisplayNameFor(model => model.State)
      @if (ViewData["PageOptions"] != null)
          {
              @Html.DropDownList("State", ViewData["PageOptions"] as IEnumerable<SelectListItem>, "(Select one)", new { @class = "TextBoxBorder" })                                         
          }
          else
          {
          <select id="State" name="State" class="TextBoxBorder">
          </select>
          }
  }
  else
  {
    // design         
  }    
}

jQuery

  $(document).ready(function () {
            $("#Country").change(function () {
                var selection = $("#Country").val();
                var dataToSend = {
                    country: selection
                };

                $.ajax({
                    type: "GET",
                    url: "/WPWebGridCart/GetStateDetails/",                    
                    data: dataToSend,
                    success: function (data) {
                        $('#State').append('<option value="' + agent + '">'  '</option>');
                    }
                });

            });
    });

Controller

public JsonResult GetStateDetails(string country)
{
var file = Path.Combine(Server.MapPath("~/App_Data"), "States.xml");
var model = new CheckoutModel
{
    States =
        from unit in XDocument.Load(file)
        .Descendants("Capital")
        .First(unit => (string)unit.Attribute("CountryName") == country)
        .Descendants("city")
    select new SelectListItem
    {
        Text = unit.Attribute("name").Value,
        Value = unit.Attribute("value").Value,
    }
};
SelectList selectList = new SelectList(model.States, "Value", "Text");
ViewData["PageOptions"] = selectList;
return Json(new { agent = ViewData["PageOptions"] }, JsonRequestBehavior.AllowGet);
}

Best Solution

$('#State').append('<option value="' + agent + '">'  '</option>');

Can't see where did you declare this agent javascript variable that you are trying to use there. You are probably getting an undefined variable error.

You will need to extract this info from your JSON result by looping through the data.agent collection:

success: function (data) {
    var statesDdl = $('#State');
    statesDdl.empty();
    $.each(data.agent, function() {
        statesDdl.append(
            $('<option/>', {
                value: this.Value,
                html: this.Text
            })
        );    
    });
}