2017-06-11 40 views
0

我有一個級聯下拉菜單,迄今爲止完美。現在我需要填充文本框,如下所示。如何在不觸發另一個AJAX調用的情況下填充和重新填充子字段?

Cascading Dropdowns

Secondary text fields based on Select Species Dropdown

Ajax代碼

$('#CommonHerpsDropdown').change(function() { 
     $('#SpeciesDropdown').empty(); 

     $.ajax({ 
      type: "POST", 
      url: '@Url.Action("GetGenericSpeciesByCommonId")', 
      datatype: "Json", 
      data: { cAnimalId: $('#CommonHerpsDropdown').val() }, 
      success: function (genericSpecies) { 
       $.each(genericSpecies, function (index, value) { 
        $('#SpeciesDropdown').append('<option value="' + value.SpeciesId + '">' + value.StandardName + '</option>'); 
        $('#ScientificClass').val(value.ScientificClassification); 
        $('#ScientificOrder').val(value.ScientificOrder); 
        $('#ScientificFamily').val(value.ScientificFamily); 
        $('#ScientificGenus').val(value.ScientificGenus); 
        $('#ScientificSpecies').val(value.ScientificSpecies); 
       }); 
      } 
     }); 

    }); 

MVC控制器Json的方法

public JsonResult GetGenericSpeciesByCommonId(int cAnimalId) 
     { 
      //Lets get the species data based on CommonHerpID. 
      var genericSpecies = (from x in _context.ReptileSpeciesList 
           where x.CommonHerpId == @cAnimalId 
           select x).OrderBy(x => x.StandardName); 
      return Json(genericSpecies); 
     } 

我的問題是,如何設置分類和訂單字段來填充/重新填充物種選擇更改而不使用另一個調用數據庫表。

+0

什麼是當前的代碼的問題?您似乎也在填充文本框 –

+0

代碼有效。但我試圖看看是否有避免$('#SpeciesDropdown')的方法。change(functon(){// Ajax調用和字段綁定)}所以我沒有必要將這些文本字段綁定多個次在單獨的更改功能 – Alex

+0

請參閱[本答案]中的第二個和第三個選項(https://stackoverflow.com/questions/28627421/better-way-to-load-2-dropdown-in-mvc/28640420#28640420) –

回答

0

您可以將數據列表對象作爲viewbag傳遞給視圖,您將在視圖中獲取數組對象,然後您可以使用filter函數到您的數組,然後您將獲得與您使用的過濾器匹配的數組,然後做的foreach函數來代替陣列的一個你得到frorm Ajax和填充您的下拉 像這樣

//ViewBag.genericSpecies is coming from _context.ReptileSpeciesList without applying any filter 
// I use json.encode to encode your list into json object 
    var AllGenericSpecies= @Html.Raw(Json.Encode(ViewBag.genericSpecies)); 
//then onchange 
$('#CommonHerpsDropdown').change(function() { 
     $('#SpeciesDropdown').empty(); 
var HerpID = $('#CommonHerpsDropdown').val(); 
//filter all generic species, apply the filter 
AllGenericSpecies.filter(function(spiece){ 
return spiece.CommonHerpId == HerpID; 
}).forEach(function(value) { 
( 
$('#SpeciesDropdown').append('<option value="' + value.SpeciesId + '">' + value.StandardName + '</option>'); 
        $('#ScientificClass').val(value.ScientificClassification); 
        $('#ScientificOrder').val(value.ScientificOrder); 
        $('#ScientificFamily').val(value.ScientificFamily); 
        $('#ScientificGenus').val(value.ScientificGenus); 
        $('#ScientificSpecies').val(value.ScientificSpecies); 
//end of foreach   
)}; 
//end of on change listener 
)});