【问题标题】:Creating Cascading dropdown in asp.net core with razor pages not working在 asp.net 核心中创建级联下拉列表,但剃须刀页面不起作用
【发布时间】:2020-11-30 16:10:46
【问题描述】:

我正在尝试首先使用 asp.net core 3.1 代码实现级联下拉列表。我有两张表,分别是车辆制造商和车辆型号。第一个下拉列表将填充品牌,并在选择任何品牌时,第二个下拉列表将填充模型。但我在模型下拉列表中一直未定义。下面是我的实现。请问我做错了什么?谢谢

IVehicleService 接口

    
    namespace Application.Common.Interfaces
    {
       public interface IVehicleService
       {
         IEnumerable<VehicleMake> GetMakes();
         IEnumerable<VehicleModel> GetModels(int categoryId);
       }
     }

车辆服务


    namespace Application.Common.Interfaces
    {
      public class VehcicleService : IVehicleService
      {
        private readonly IApplicationDbContext _dbContext;
        public VehcicleService(IApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public IEnumerable<VehicleMake> GetMakes()
        {
            IEnumerable<VehicleMake>  makes = _dbContext.VehicleMakes.ToList();
            return makes;       
        }
        public IEnumerable<VehicleModel> GetModels(int MakeId)
        {
            IEnumerable<VehicleModel> model = _dbContext.VehicleModels.Where(x => x.VehicleMakeId == MakeId).ToList();            
            return model;
        }
    }
     }

我的模特页面

namespace Wbc.WebUI.Areas.Tools.Pages
{
    
    public class SearchByMakeModel : PageModel
    {
       private readonly IVehicleService _vehicleService;
        public SearchByMakeModel(IVehicleService vehicleService)
        {           
            _vehicleService = vehicleService;
        }
        [BindProperty(SupportsGet = true)]
        public int MakeId { get; set; }
        public int ModelId { get; set; }
        public SelectList MakeListdll { get; set; }

       public void OnGet()
        {
            MakeListdll = new SelectList(_vehicleService.GetMakes(), nameof(VehicleMake.Id), 
            nameof(VehicleMake.Name));
        }

        public JsonResult OnGetSubCategories()
        {
            return new JsonResult(_vehicleService.GetModels(MakeId));
        }
    }
}

我的剃刀标记

 <select asp-for="MakeId" asp-items="Model.MakeListdll">
   <option value=""></option>
   </select>

   <select asp-for="ModelId">                            
    </select>

接口及其实现在Startup中注册到依赖注入系统:

services.AddTransient<IVehicleService, VehcicleService>();

我的 Ayax 电话

@section scripts{
    <script type="text/javascript">
        $(function () {
            $("#MakeId").on("change", function() {
                var makeId = $(this).val();
                $("#ModelId").empty();
                $("#ModelId").append("<option value=''>Select Model</option>");
                $.getJSON(`?handler=OnGetModels&MakeId=${makeId}`, (data) => {
                    $.each(data, function (i, item) {
                        $("#ModelId").append(`<option value="${item.Id}">${item.Name}</option>`);
                    });
                });
            });
        });
    </script>
}

【问题讨论】:

    标签: sql-server ajax asp.net-core razor-pages clean-architecture


    【解决方案1】:

    首先,在js的$.getJson中,需要将handler改为SubCategories,因为需要输入OnGetSubCategories才能获取VehicleModel数据。

    但我在模型下拉列表中一直未定义

    还有一点很重要的是,在core中,ajax返回json时,字段名默认会改为驼峰式,所以需要修改item后面的字段名首字母转为小写,如:${item.id}${item.name}

    由于您没有提供 VehicleModel 类,这是我的自定义 VehicleModel 类:

       public class VehicleModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int VehicleMakeId { get; set; }
        }
    

    这里是js:

    @section scripts{
        <script type="text/javascript">
            $(function () {
                $("#MakeId").on("change", function () {
                    var makeId = $(this).val();
                    $("#ModelId").empty();
                    $("#ModelId").append("<option value=''>Select Model</option>");
                    $.getJSON(`?handler=SubCategories&MakeId=${makeId}`, (data) => {
                        $.each(data, function (i, item) {
                            $("#ModelId").append(`<option value="${item.id}">${item.name}</option>`);
                        });
                    });
                });
            });
        </script>
    }
    

    更新

    如果不希望返回的json中的字段名变成驼峰式,那么可以在startup中添加如下语句取消:

    services.AddMvc().AddJsonOptions(jsonOptions =>
            {
                jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
            });
    

    这是测试结果:

    【讨论】:

    • 感谢@Yongqing Yu。这真的很有帮助
    【解决方案2】:

    在处理 AJAX 请求时,请务必检查 browser's developer tools 中的网络选项卡。然后你会看到请求返回 404 Not Found。您在 PageModel 中有一个名为 OnGetSubCategories 的处理程序,但您的 AJAX 调用处理程序参数名为 OnGetModels

    一旦您决定要使用哪个名称,您应该在将处理程序名称传递给 AJAX 查询字符串时删除 OnGetOnPost 部分:

    $.getJSON(`?handler=Subcategories&MakeId=${makeId}`
    

    有关使用命名处理程序方法的更多信息:https://www.learnrazorpages.com/razor-pages/handler-methods#named-handler-methods

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 1970-01-01
      • 2020-11-09
      • 2019-07-24
      • 1970-01-01
      • 2021-01-05
      • 2019-01-19
      • 2021-10-03
      • 2020-12-08
      相关资源
      最近更新 更多