级联下拉列表 - 我错过了什么?

Cascading DropDown Lists - What am I missing?

提问人:MelB 提问时间:2/13/2023 最后编辑:MelB 更新时间:2/15/2023 访问量:111

问:

我一直在关注有关如何将一个下拉列表级联从另一个下拉列表级联的教程,但无法使其工作。任何协助将不胜感激。我不太了解javascript,所以捏造了我的方式。我不完全确定我的 URL 部分是否正确?

我正在尝试填充 ArrestDept 下拉列表,然后根据所选的 ArrestDept 筛选和填充 ArrestOfficer 下拉列表。

这是我到目前为止所拥有的:

相关观点:

                <td style="width: 20%">
                        <div class="mb-3">
                            <label asp-for="Incident.ArrestDept"></label>
                            <select id="agency" class="form-select"></select>
                        </div>
                </td>
                <td style="width: 20%">
                    <div class="mb-3">
                        <label asp-for="Incident.ArrestOfficer"></label>
                        <select id="officer" class="form-select"></select>
                    </div>
                </td>

@section视图底部的脚本:

@section Scripts
{
    <partial name="_ValidationScriptsPartial" />

    <script type="text/javascript">
        $(document).ready(function () {
        $('#agency').attr('disabled', true);
        $('#officer').attr('disabled', true);
        LoadAgencies();
    });

    function LoadAgencies() {
        $('#agency').empty();

        $.ajax({
            url: '/CreateModel/GetAgencies',
            success: function (response) {
                if (response != null && response != undefined && response.length > 0) {
                    $('#agency').attr('disabled', false);
                    $('#agency').append('
                        <option>---Select Arresting Agency---</option>');
                    $('#officer').append('
                        <option>---Select Arresting Officer---</option>');
                    $.each(response, function (i, data) {
                        $('#agency').append('
                        <option value=' + data.id + '>' + data.AgencyName + '</option>');
                    });
                }
                else {
                    $('#agency').attr('disabled', true);
                    $('#officer').attr('disabled', true);
                    $('#agency').append('
                        <option>---Arresting Agencies Not Available---</option>');
                    $('#officer').append('
                        <option>---Arresting Officers Not Available---</option>');
                }
            },
            error: function (error) {
                alert(error);
            }
        });
    }
    }
    function LoadOfficers(agencyId) {
        $('#officer').empty();

        $.ajax({
            url: '/CreateModel/GetOfficers?Id=' + agencyId,
            success: function (response) {
                if (response != null && response != undefined && response.length > 0) {
                    $('#officer').attr('disabled', false);
                    $('#officer').append('
                        <option>---Select Arresting Officer---</option>');
                    $.each(response, function (i, data) {
                        $('#officer').append('
                        <option value=' + data.id + '>' + data.OfficerDisplayName + '</option>');
                    });
                }
                else {
                    $('#officer').attr('disabled', true);
                    $('#officer').append('
                        <option>---Arresting Officers Not Available---</option>');
            }
        },
        error: function (error) {
            alert(error);
        }
    });
    </script>

    }

视图的.cs:

using DWITracker.Data;
using DWITracker.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace DWITracker.Pages.Incidents;

[BindProperties]

public class CreateModel : PageModel
{
    private readonly ApplicationDbContext _db;
    public Incident Incident { get; set; }
    public CreateModel(ApplicationDbContext db)
    {
        _db = db;
    }

    public IEnumerable<City> DisplayCityData { get; set; }
    public IEnumerable<County> DisplayPIAddressCountyData { get; set; }
    public IEnumerable<Ethnicity> DisplayPIEthnicityData { get; set; }
    public IEnumerable<ArrestMethod> DisplayArrestMethodData { get; set; }
    public IEnumerable<Test> DisplayTestGivenData { get; set; }
    public IEnumerable<Charge> DisplayChargeData { get; set; }
    public IEnumerable<DrinkLocation> DisplayLastDrinkData { get; set; }
    public IEnumerable<DrugRecognitionExpert> DisplayDrugExpertData { get; set; }

    public async Task OnGet()
    {
        await _db.City.Select(a => a.CityName).ToListAsync();
        DisplayCityData = await _db.City.ToListAsync();
        await _db.County.Select(a => a.CountyName).ToListAsync();
        DisplayPIAddressCountyData = await _db.County.ToListAsync();
        await _db.Ethnicity.Select(a => a.EthnicityName).ToListAsync();
        DisplayPIEthnicityData = await _db.Ethnicity.ToListAsync();
        await _db.ArrestMethod.Select(a => a.ArrestMethodDesc).ToListAsync();
        DisplayArrestMethodData = await _db.ArrestMethod.ToListAsync();
        await _db.Test.Select(a => a.TestDesc).ToListAsync();
        DisplayTestGivenData = await _db.Test.ToListAsync();
        await _db.Charge.Select(a => a.ChargeCode).ToListAsync();
        DisplayChargeData = await _db.Charge.ToListAsync();
        await _db.DrinkLocation.Select(a => a.LastDrinkLocation).ToListAsync();
        DisplayLastDrinkData = await _db.DrinkLocation.ToListAsync();
        await _db.DrugRecognitionExpert.Select(a => a.DrugRecExpert).ToListAsync();
        DisplayDrugExpertData = await _db.DrugRecognitionExpert.ToListAsync();
    }

    public JsonResult GetAgencies()
    {
        var agencies = _db.Agency.OrderBy(x => x.AgencyName).ToList();
        return new JsonResult(agencies);
    }

    public JsonResult GetOfficers(int id)
    {
        var officers = _db.Officer.Where(x => x.Agency.Id == id).OrderBy(x => x.OfficerDisplayName).ToList();
        return new JsonResult(officers);
    }


    public async Task<IActionResult> OnPost()
    {
        if (ModelState.IsValid)
        {
            _db.Incident.Add(Incident);
            await _db.Incident.AddAsync(Incident);
            await _db.SaveChangesAsync();
            TempData["success"] = "Incident added successfully.";
            return RedirectToPage("Index");
        }
        return Page();
    }

}

事件模型的相关部分:

public class Incident
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "Arresting Dept")]
        public string? ArrestDept { get; set; }
        [Display(Name = "Arresting Officer")]
        public string? ArrestOfficer { get; set; }
    }

代理模式的相关部分:

    public class Agency
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [Display(Name = "Agency")]
        public string AgencyName { get; set; }
    }

军官模型的相关部分:

    public class Officer
    {
        [Key]
        public int Id { get; set; }
        [Display(Name ="Officer Name (Last, First, MI)")]
        public string? OfficerDisplayName { get; set; }
        [Display(Name = "First Name")]
        public string? OfficerFirstName { get; set; }
        [Display(Name = "MI")]
        public string? OfficerMiddleInitial { get; set; }
        [Display(Name = "Last Name")]
        public string? OfficerLastName { get; set; }
        public Agency Agency { get; set; }
    }

另一个问题是,使用一个表是否更容易完成,因为我可以轻松地将官员和机构模型合并到一个表中。实际上,这将是我的偏好,但一直无法找到解决如何执行此操作的教程。

我想我可以很容易地消除代理模型,只需将它们组合在军官模型上,所以编辑了将代理添加到军官模型中。一个“OfficerAgency”可能有很多官员。

using System.ComponentModel.DataAnnotations;

namespace DWITracker.Model
{
    public class Officer
    {
        [Key]
        public int Id { get; set; }
        [Display(Name ="Officer Name (Last, First, MI)")]
        public string? OfficerDisplayName { get; set; }
        [Display(Name = "First Name")]
        public string? OfficerFirstName { get; set; }
        [Display(Name = "MI")]
        public string? OfficerMiddleInitial { get; set; }
        [Display(Name = "Last Name")]
        public string? OfficerLastName { get; set; }
        [Display(Name = "Agency")]
        public string? OfficerAgency { get; set; }
        [Display(Name = "Added/Updated By")]
        public string UpdatedBy { get; set; }
        [Display(Name = "Date Added/Updated")]
        [DataType(DataType.Date)]
        public DateTime UpdateDate { get; set; }
        public Agency Agency { get; set; }
    }
}

这将如何改变代码?希望它能让它更简单?

只是不确定我将如何更改 .cs 以在单个表上工作,特别是 OnGetOfficers(int id):

    public JsonResult OnGetGetAgencies()
    {
        var agencies = _db.Officer.OrderBy(x => x.OfficerAgency).ToList();
        return new JsonResult(agencies);
    }

    public JsonResult OnGetGetOfficers(int id)
    {
        var officers = _db.Officer.Where(x => x.OfficerAgency == id).OrderBy(x => x.OfficerDisplayName).ToList();
        return new JsonResult(officers);
    }
javascript asp.net-core 剃刀页 级联下拉

评论


答:

0赞 Rena 2/14/2023 #1

您的 js 在这里包含多个问题:

1.您添加了一个额外的 in 函数。}LoadAgencies

2.你错过了一个功能。}LoadOfficers

3.你可以看到每次使用时,这个方法中的字符串你总是写在一个新行中,你需要在JavaScript中使用如下运算符连接字符串(只是一个例子,你的js包含很多这种类型的问题):append+

$('#agency').append(''+
    '<option>---Select Arresting Agency---</option>');

或者只是移动到同一行:

$('#agency').append('<option>---Select Arresting Agency---</option>');

4.响应数据为驼峰大小写格式,例如,您需要更改为:data.AgencyNamedata.agencyName

$('#agency').append('<option value=' + data.id + '>' + data.agencyName + '</option>');

5.Razor Pages路由不像MVC,Razor Pages使用和处理Http Get和Post请求。并且 url 与 PageModelName 和文件夹名称相关,例如:in folder,url 是:。如果它只是在文件夹中,则 url 为:。如果需要当前 PageModel 中的另一个 OR 方法,则需要定义方法名称,例如:OnGetHandlerName 或 OnPostHandlerName。网址为:.OnGetOnPostIndexModelPages/Student/Student/IndexPages/IndexGetPost/FolderName/PageModelName?handler=HandlerName


整个工作代码:

@page
@model CreateModel
<table>
    <tr>
        <td style="width: 20%">
            <div class="mb-3">
                <label asp-for="Incident.ArrestDept"></label>
                                                                 @*add onchange function*@
                <select id="agency" class="form-select" onchange="LoadOfficers(this.value)"></select>  
            </div>
        </td>
        <td style="width: 20%">
            <div class="mb-3">
                <label asp-for="Incident.ArrestOfficer"></label>
                <select id="officer" class="form-select"></select>
            </div>
        </td>
    </tr>
</table>

页面中的 JS:

@section Scripts
    {
    <partial name="_ValidationScriptsPartial" />

    <script type="text/javascript">
            $(document).ready(function () {
            $('#agency').attr('disabled', true);
            $('#officer').attr('disabled', true);
            LoadAgencies();
        });

        function LoadAgencies() {
            $('#agency').empty();

            $.ajax({
                url: '/Create?handler=GetAgencies',   //change here....
                success: function (response) {
                    if (response != null && response != undefined && response.length > 0) {
                        $('#agency').attr('disabled', false);
                        $('#agency').append('<option>---Select Arresting Agency---</option>');//change to one line...
                        $('#officer').append('<option>---Select Arresting Officer---</option>');//change to one line...
                        $.each(response, function (i, data) {
                                                                                //change to camel case here...
                            $('#agency').append('<option value=' + data.id + '>' + data.agencyName + '</option>');
                        });
                    }
                    else {
                        $('#agency').attr('disabled', true);
                        $('#officer').attr('disabled', true);
                        $('#agency').append('<option>---Arresting Agencies Not Available---</option>');//change to one line...
                        $('#officer').append('<option>---Arresting Officers Not Available---</option>');//change to one line...
                    }
                },
                error: function (error) {
                    alert(error);
                }
            });
        }
        //}
        function LoadOfficers(agencyId) {
            $('#officer').empty();

            $.ajax({
                url: '/Create?handler=GetOfficers&Id=' + agencyId,  //change here....
                success: function (response) {
                    if (response != null && response != undefined && response.length > 0) {
                        $('#officer').attr('disabled', false);
                        $('#officer').append('<option>---Select Arresting Officer---</option>'); //change to one line...
                        $.each(response, function (i, data) {
                                                                                     //change to camel case here...
                            $('#officer').append('<option value=' + data.id + '>' + data.officerDisplayName + '</option>');
                        });
                    }
                    else {
                        $('#officer').attr('disabled', true);
                        $('#officer').append('<option>---Arresting Officers Not Available---</option>'); //change to one line...
                }
            },
            error: function (error) {
                alert(error);
            }
        });
    }  //add this '}'
    </script>

}

PageModel(页面模型)

public JsonResult OnGetGetAgencies()
{
    //...
    return new JsonResult(agencies);
}

public JsonResult OnGetGetOfficers(int id)
{
    //...
    return new JsonResult(officers);
}

评论

0赞 MelB 2/14/2023
非常感谢您非常清楚的解释。:)我仍然收到一条警告消息 [object Object],但两个 DDL 都显示为灰色。不确定我现在错过了什么?
0赞 MelB 2/14/2023
添加了修订后的官员模型,其中包括机构名称。假设我需要反映这一点的唯一更改是 OnGetGetAgencies() 来反映_db。军官而不是_db。具有新公共字符串名称的机构?
0赞 MelB 2/14/2023
那么,我实际上也可以消除公共机构机构{ get; set; },对吗?
0赞 Rena 2/15/2023
您只在错误函数中使用 Alert,因此您的 AJAX 或后端代码似乎有问题。请设置断点以检查请求是否命中响应。然后检查 Visual Studio 中的面板是否有任何错误,并在浏览器中按 F12 检查面板是否有任何错误。OutputConsole
1赞 MelB 2/23/2023
发现URL不正确。将 /page 名称添加到 URL 的开头,它起作用了。感谢您的帮助!