title: better way to load 2 dropdown in mvc
body: <p>This is how i am loading on page load state and city dropdown:</p>
  
  <p><strong>My Controller method</strong>:</p>
  
  <p>This is the first method which is calling when page is loaded.</p>
  
  <pre><code>public ActionResult Index()
  {
      var states = GetStates();
      var cities =  Enumerable.Empty&lt;SelectListItem&gt;();
      ViewBag.States = states;
      ViewBag.Cities = cities;
  }
  
  private IEnumerable&lt;SelectListItem&gt; GetStates()
  {
      using (var db = new DataEntities())
      {
          return db.States.Select(d =&gt; new SelectListItem { Text = d.StateName, Value =d.Id.ToString() });
      }
  }
  
  [HttpGet]
  public ActionResult GetCities(int id)
  {
      using (var db = new DataEntities())
      {
          var data = db.Cities.Where(d=&gt;d.StateId==id).Select(d =&gt; new { Text = d.CityName, Value = d.Id }).ToList();
          return Json(data, JsonRequestBehavior.AllowGet);
      }
  }
  </code></pre>
  
  <p><strong>My View</strong>:</p>
  
  <pre><code>IEnumerable&lt;SelectListItem&gt; States = ViewBag.States;
  IEnumerable&lt;SelectListItem&gt; Cities = ViewBag.Cities;
  
  @Html.DropDownList("State", States, "Select State", new { onchange="loadCities(this)"})
  @Html.DropDownListFor(m =&gt; m.CityId, Cities, "Select City", new { id="ddlCity"})
  function loadCities(obj) {
              $.ajax({
                  url: "/Home/GetCities",
                  data: { id: $(obj).val() },
                  contentType:"application/json",
                  success:function(responce){                   
                      var html = '&lt;option value="0"&gt;Select City&lt;/option&gt;';
                      $(responce).each(function () {
                          html += '&lt;option value="'+this.Value+'"&gt;'+this.Text+'&lt;/option&gt;'
                      });
                      $("#ddlCity").html(html);
                  }
              });
          }
  </code></pre>
  
  <p>Any better way then this to load state and city dropdown?</p>
  
  <pre><code>public class HomeController : Controller
      {
          public ActionResult Index(int id=0)
          {
              Person model = null;
              var states = GetStates().ToList();
              var cities =  Enumerable.Empty&lt;SelectListItem&gt;();
              if (id &gt; 0)
              {
                  using (var db = new  DataEntities())
                  {
                      model = db.People.Include("City").FirstOrDefault(d =&gt; d.Id == id);
                      if (model == null)
                          model = new Person();
                      else
                      {
                         states.First(d =&gt; d.Value == model.City.StateId.ToString()).Selected = true;
                         cities = db.Cities.Where(d =&gt; d.StateId == model.City.StateId).ToList().Select(d =&gt; new SelectListItem { Text = d.CityName,Value=d.Id.ToString(),Selected=d.Id==model.CityId });
                      }
  
                  }
              }
              else
              {
                  model = new Person();
              }
              ViewBag.States = states;
              ViewBag.Cities = cities;
              ViewBag.Persons = GetPersons();
              return View(model);
          }
  
          [HttpGet]
          public ActionResult GetCities(int id)
          {
              using (var db = new DataEntities())
              {
                  var data = db.Cities.Where(d=&gt;d.StateId==id).Select(d =&gt; new { Text = d.CityName, Value = d.Id }).ToList();
                  return Json(data, JsonRequestBehavior.AllowGet);
              }
          }
  
          public ActionResult SavePersonDetail([Bind(Exclude = "Id")] Person model)
          {
  
              // var employeeDal= new Emploee();
              //employee.firstname=model.
  
              if (ModelState.IsValid)
              {
                  var Id = model.Id;
                  int.TryParse(Request["Id"], out Id);
              using (var db = new DataEntities())
              {
                  if (Id &gt; 0)
                  {
                      var person = db.People.FirstOrDefault(d =&gt; d.Id == Id);
                      if (person != null)
                      {
                          model.Id = Id;
                          db.People.ApplyCurrentValues(model);
                      }
                  }
                  else
                  {
                      db.People.AddObject(model);                    
                  }
                  db.SaveChanges();
                  }               
              }
              if (!Request.IsAjaxRequest())
              {
                  ViewBag.States = GetStates();
                  ViewBag.Persons = GetPersons();
                  ViewBag.Cities = Enumerable.Empty&lt;SelectListItem&gt;();
                  return View("Index");
              }
              else
              {
                  return PartialView("_personDetail",GetPersons());
              }
          }
  
          public ActionResult Delete(int id)
          {
              using (var db = new DataEntities())
              {
                  var model = db.People.FirstOrDefault(d =&gt; d.Id == id);
                  if (model != null)
                  {
                      db.People.DeleteObject(model);
                      db.SaveChanges();
                  }                
              }
              if (Request.IsAjaxRequest())
              {
                  return Content(id.ToString());
              }
              else
              {
                  ViewBag.States = GetStates();
                  ViewBag.Persons = GetPersons();
                  ViewBag.Cities = Enumerable.Empty&lt;SelectListItem&gt;();
                  return View("Index");
              }
          }
  
          private IEnumerable&lt;SelectListItem&gt; GetStates()
          {
              using (var db = new DataEntities())
              {
                 return db.States.ToList().Select(d =&gt; new SelectListItem { Text = d.StateName, Value =d.Id.ToString() });
              }
          }
  
          private IEnumerable&lt;Person&gt; GetPersons()
          {
              using (var db = new DataEntities())
              {
                  return db.People.Include("City").Include("City.State").ToList();
              }
          }
  
          public ActionResult HomeAjax()
          {
              ViewBag.States = GetStates();
              ViewBag.Cities = Enumerable.Empty&lt;SelectListItem&gt;();
              using (var db = new DataEntities())
              {
                  var data = db.States.Include("Cities").Select(d =&gt; new { Id = d.Id, Name = d.StateName, Cities = d.Cities.Select(x =&gt; new { Id=x.Id,Name=x.CityName}) }).ToList();
                  ViewBag.CityStateJson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(data);
              }
              ViewBag.Persons = GetPersons();
              return View();
          }
      }
  
  
  @model IEnumerable&lt;Person&gt;
  &lt;div&gt;
      &lt;table&gt;
          &lt;tr&gt;
              &lt;th&gt;
                  First Name
              &lt;/th&gt;
              &lt;th&gt;
                  Last Name
              &lt;/th&gt;
              &lt;th&gt;
                  Email
              &lt;/th&gt;
              &lt;th&gt;
                  City
              &lt;/th&gt;
              &lt;th&gt;
                  State
              &lt;/th&gt;
              &lt;th&gt;
                  Edit
              &lt;/th&gt;
          &lt;/tr&gt;
      @if (Model.Count() == 0)
      {
          &lt;tr&gt;
              &lt;td colspan="6"&gt;
                  &lt;h3&gt;No data available&lt;/h3&gt;
              &lt;/td&gt;
          &lt;/tr&gt;
      }
      else { 
      foreach (var item in Model) { 
          &lt;tr data-id="@item.Id"&gt;
              &lt;td data-id="fn"&gt;@item.FirstName&lt;/td&gt;
              &lt;td data-id="ln"&gt;@item.LastName&lt;/td&gt;
              &lt;td data-id="email"&gt;@item.Email&lt;/td&gt;
              &lt;td data-id="cn"&gt;@item.CityName&lt;input type="hidden" value="@item.CityId" /&gt;&lt;/td&gt;
              &lt;td&gt;@item.StateName&lt;/td&gt;
              &lt;td&gt;
                  @if (ViewBag.Title == "Home Ajax" || Request.IsAjaxRequest())
                  {
                      &lt;a href="javascript:void(0);" onclick="Edit(this,@item.Id);"&gt;Update&lt;/a&gt;
                      &lt;span&gt;@Ajax.ActionLink("Delete", "Delete", new { id = item.Id }, new AjaxOptions {OnSuccess="deleteSuccess",OnBegin="showLoader",OnComplete="hideLoader" })&lt;/span&gt;
  
                  }
                  else { 
                      &lt;span&gt;@Html.ActionLink("Update", "Index", new { id = item.Id })&lt;/span&gt;
                      &lt;span&gt;@Html.ActionLink("Delete", "Delete", new { id = item.Id })&lt;/span&gt;
                  }
  
              &lt;/td&gt;
          &lt;/tr&gt;
      }
  
      }
          &lt;/table&gt;
  &lt;/div&gt;
  
  @model Person
  
  @{
      ViewBag.Title = "Home Ajax";
      IEnumerable&lt;Person&gt; persons = ViewBag.Persons;
      IEnumerable&lt;SelectListItem&gt; States = ViewBag.States;
      IEnumerable&lt;SelectListItem&gt; Cities = ViewBag.Cities;
      IEnumerable&lt;State&gt; fullStates=ViewBag.CityStates;
  
  }
  
  @section featured {
      &lt;section class="featured"&gt;
          &lt;div class="content-wrapper"&gt;
              &lt;hgroup class="title"&gt;
                  &lt;h1&gt;@ViewBag.Title.&lt;/h1&gt;                
              &lt;/hgroup&gt;            
          &lt;/div&gt;
      &lt;/section&gt;
  }
  
  @section styles{
      &lt;style type="text/css"&gt;
         td,th {
              border:1px solid;
              padding:5px 10px;
          }
  
          select {
             padding:5px 2px;
             width:310px;
             font-size:16px;
          }
      &lt;/style&gt;
  }
  
  @section scripts{
      @Scripts.Render("~/bundles/jqueryval")
      &lt;script type="text/javascript"&gt;
  
          var jsonArray = @Html.Raw(ViewBag.CityStateJson)
  
          function clearValues() {
              $("input[type='text'],select").val('');
              $("input[type='hidden'][name='Id']").val(0);
          }
  
          function loadCities(obj) {
  
              for (var i = 0; i &lt; jsonArray.length; i++) {
                  if (jsonArray[i].Id == parseInt($(obj).val())) {
                      fillCity(jsonArray[i].Cities);
                      break;
                  }
              }
          }
  
          function Edit(obj, Id) {
              //  alert("hi")
              $("input[type='hidden'][name='Id']").val(Id);
              var tr = $(obj).closest("tr");
              $("#txtfirstName").val($("td[data-id='fn']", tr).text().trim());
              $("#txtlastName").val($("td[data-id='ln']", tr).text().trim());
              $("#txtemail").val($("td[data-id='email']", tr).text().trim());
              var city = $("td[data-id='cn'] input[type='hidden']", tr).val();
              var state;
              for (var i = 0; i &lt; jsonArray.length; i++) {
                  for (var j = 0; j &lt; jsonArray[i].Cities.length; j++) {
                      if (jsonArray[i].Cities[j].Id == parseInt(city)) {
                          state = jsonArray[i].Id;
                          break;
                      }
                  }
                  if (state) {
                      fillCity(jsonArray[i].Cities);
                      break;
                  }
              }
              $("#ddlState").val(state);
              $("#ddlCity").val(city);
          }
  
          function fillCity(obj) {
              var html = '&lt;option value="0"&gt;Select City&lt;/option&gt;';
              $(obj).each(function () {
                  html += '&lt;option value="' + this.Id + '"&gt;' + this.Name + '&lt;/option&gt;'
              });
              $("#ddlCity").html(html);
          }
  
          function deleteSuccess(responce) {
              alert("record deleted successfully");
              $("tr[data-id='" + responce + "']").remove();
          }
  
          function insertSuccess() {
              alert("Record saved successfully");
              clearValues();
          }
  
          function showLoader() {
              $("#overlay").show();
          }
          function hideLoader() {
              $("#overlay").hide();
          }
      &lt;/script&gt;
  }
  
  &lt;h3&gt;Add Personal Detail&lt;/h3&gt;
  @using (Ajax.BeginForm("SavePersonDetail", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "personList" ,OnSuccess="insertSuccess",OnBegin="showLoader",OnComplete="hideLoader"}))
  {
      @Html.HiddenFor(m =&gt; m.Id);
  &lt;ol class="round"&gt;
      &lt;li&gt;       
          @Html.LabelFor(m =&gt; m.FirstName)
          @Html.TextBoxFor(m =&gt; m.FirstName, new { id = "txtfirstName" })
          @Html.ValidationMessageFor(m =&gt; m.FirstName)
      &lt;/li&gt;
      &lt;li&gt;
      @Html.LabelFor(m =&gt; m.LastName)
          @Html.TextBoxFor(m =&gt; m.LastName, new { id = "txtlastName" })
          @Html.ValidationMessageFor(m =&gt; m.LastName)
          &lt;/li&gt;
      &lt;li&gt;
         @Html.LabelFor(m =&gt; m.Email)
          @Html.TextBoxFor(m =&gt; m.Email, new { id = "txtemail" })
          @Html.ValidationMessageFor(m =&gt; m.Email)
      &lt;/li&gt;
  
      &lt;li&gt;
          @Html.Label("State")
         @Html.DropDownList("State", States, "Select State", new { onchange = "loadCities(this)", id = "ddlState" })       
      &lt;/li&gt;
      &lt;li&gt;
           @Html.LabelFor(m =&gt; m.CityId)
          @Html.DropDownListFor(m =&gt; m.CityId, Cities, "Select City", new { id = "ddlCity" })
          @Html.ValidationMessageFor(m =&gt; m.CityId)
      &lt;/li&gt;
  &lt;/ol&gt;
      &lt;input type="submit" value="Save" /&gt;
      &lt;input type="button" value="Cancel" onclick="clearValues();"/&gt;
  }
  
     &lt;h2&gt;
          Person List
      &lt;/h2&gt;
  &lt;div style="position:fixed;text-align:center;top:0;bottom:0;left:0;right:0;z-index:10;background-color:black;opacity:0.6;display:none;" id="overlay"&gt;
      &lt;img style="position:relative;top:370px" src="~/Images/ajax-loader.gif" /&gt;
  &lt;/div&gt;
  &lt;div id="personList"&gt;
      @Html.Partial("_personDetail", persons)
      &lt;/div&gt;
  </code></pre>