2012-05-15 29 views
0

我有兩個dropdownlistfor,和他們的第二個應該基於第一dropdownlist如何填寫下拉列表基於另一個下拉列表的數組,使用jQuery的MVC

我一直的值來填充數組試圖按照Darins Answer here,但我有問題得到第二個dropdownlistfor工作和充滿我的陣列。我的第二個Dropdownlisfor沒有被填滿,相反,它消失了。

這是我使用JSON

<script type="text/javascript"> 
    $(function() { 
     $('#teamname').change(function() { 
      var selectednametext = $(this).find("option:selected").text(); 
      $.getJSON('@Url.Action("TeamName")', { TeamName: selectednametext }, function (persons) { 
       var selectedpersons = $('#personname'); 
       selectedpersons.empty(); 
       $.each(persons, function (index, person) { 
        selectedpersons.append(
        $('<option/>') 
         .attr('value', person.name) 
         .text(person.name) 
       ); 
      }); 
     }); 
    }); 
}); 
</script> 

腳本這是我DropdownListfor在我看來:

<p>Team</p> 
     <div class="editor-field" id="teamname"> 
      @Html.DropDownListFor(model => model.TeamName, Model.Teams, "Select Team", new { @class = "selectstyle" }) 
      @Html.ValidationMessageFor(model => model.TeamName) 
     </div> 
     <p>Person</p> 
     <div class="editor-field" id="personname"> 
      @Html.DropDownListFor(model => model.PersonName, Model.Person, "Select Person", new { @class = "selectstyle", @disabled = "disabled" }) 
      @Html.ValidationMessageFor(model => model.PersonName) 

這怎麼我的陣列是越來越充滿在我的控制器:

public ActionResult TeamName(string teamname) 
    { 
     if (teamname == "Team A") 
     { 
      System.Collections.ArrayList teamArray = new System.Collections.ArrayList(); 

      new ConsultantContext(new Uri("http://foo/persons"), ConsultantContext.Format.Json) 
      .Consultant 
      .Where(x => x.Team == "Team A") 
      .OrderBy(x => x.DisplayName) 
      .ToList() 
      .ForEach(item => 
      { 
      teamArray.Add(item.DisplayName); 
      }); 

      return Json(teamArray, JsonRequestBehavior.AllowGet); 
     }// and same goes with arrays for Team B and Team C 

各種幫助表示感謝,提前致謝!

回答

1

$('#teamname')與您的下拉列表的ID不符。請確保你已經在你的標記分配相同的ID:

@Html.DropDownListFor(
    model => model.TeamName, 
    Model.Teams, 
    "Select Team", 
    new { id = "teamname", @class = "selectstyle" } 
) 

同代表真正的$('#personname');選擇。您應該修正您的標記,以便這些選擇器與您的DOM元素相對應。

另外,你爲什麼使用ArrayList?這是史前的。使用強類型的收藏品:

public ActionResult TeamName(string teamname) 
{ 
    var consultants = new ConsultantContext(
     new Uri("http://foo/persons"), 
     ConsultantContext.Format.Json 
    ) 
    .Consultant 
    .Where(x => x.Team == teamname) 
    .OrderBy(x => x.DisplayName) 
    .ToList() 
    .Select(x => new 
    { 
     name = x.DisplayName 
    }); 

    return Json(consultants, JsonRequestBehavior.AllowGet); 
} 
+0

我已經修復了該ID的匹配現在。但是我的腳本仍然沒有填充我的第二個'dropdownlist'數組。它是空的。 –

+0

你看過FireBug嗎?你看到AJAX請求了嗎?服務器迴應什麼?確保你的jQuery選擇器返回值。您可以使用FireBug將斷點放入JavaScript中,並逐步進行調試。 –

+0

感謝您的幫助。一旦我改變爲強類型集合它的工作 –

相關問題