如何在不启动另一个AJAX调用的情况下填充和重新填充子字段?

时间:2017-06-11 14:38:22

标签: json ajax asp.net-mvc

我有一个级联下拉列表,到目前为止完美无缺。现在我需要填充文本框,如下所示。

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);
        }

我的问题是如何设置分类和订单字段,以便在物种选择更改时填充/重新填充,而无需再使用对db表的另一个调用。

1 个答案:

答案 0 :(得分:0)

您可以将数据列表对象作为视图包传递给视图,您将在视图中获取数组对象,然后您可以使用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 
)});