首页 > 解决方案 > 如何过滤 mvc Razor 中下拉列表更改的记录

问题描述

我有一个要求,比如我有一个绑定在页面加载上的供应商列表,并且我还有下拉列表,用于过滤下拉列表更改时的供应商记录。

我的观点:

<div class="half-left">
            @Html.DropDownListFor(x => x.subCatObj.SubCategory_Id, Model.GetAllSubCategory, "--Select--", new { @id = "subCategory", @class = "contactField" })
        </div>


        @foreach (var vendor in Model.GetAllVendors)
        {
              @vendor.VendorCompanyName  
        }

我的问题是如何过滤下拉更改的记录..请帮助

标签: jqueryajaxasp.net-mvcpartial-views

解决方案


这是一个可能的解决方案:

在你的 CSS 中:

//CSS class to use on your option elements to make their display property none
.hiddenOption{
   display:none;
}

如果使用要导入视图的外部 javascript 文件或视图中的脚本标记,使用 JQuery,请使用 document.ready 将更改事件附加到子类别下拉列表:

//Use document.ready in JQuery to add change handler to drop down
$(document).ready(function(){
    $('#subCategory').on('change', function(){
         //Call your filtering function here
         FilterVenders();
    });
});

//Declare and define a function for doing the filtering in your external
//script or in your script tag of View
function FilterVenders(){
    //As I don't know what kind of logic you use to filter, you need to
    //Work on this portion
    const subCategoryValue = $('#subCategory').val();
    const subCategoryText = $('#subCategory option:selected').text();

    //Loop all the options in your drop down list and apply the class
    //which makes their display as none (hide the options)
    $('#subCategory > option').each(function(){
         //If the option is not to be displayed, add the class
         //This is where you need to step in and provide the filtering logic
         if(condition){
            //Check if option is already hidden, if not add the class to hide it
             if(!$(this).hasClass('hiddenOption')){
                 $(this).addClass('hiddenOption');
             }
          }else{
             //Check if option is hidden, if so, remove class to unhide it
             if($(this).hasClass('hiddenOption')){
                 $(this).removeClass('hiddenOption');
             } 
          }
     });
}

推荐阅读