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

huangapple go评论72阅读模式
英文:

Cascading DropDown Lists - What am I missing?

问题

I've translated the code portions as you requested. Please note that if you need any specific help with the code, you can ask questions, but I won't provide a full explanation or solution here.

I've been following a tutorial on how to have one dropdown cascade from another, but am unable to get it to work. Any assistance would be greatly appreciated. I do not know javascript well, so fudging my way thru. I am not entirely sure I have the URL portion correct?

I am attempting to populate the ArrestDept dropdown and then filter and populate the ArrestOfficer dropdown based on the selected ArrestDept.

Here is what I have so far:

Relevant Part of View:
            <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 Scripts at bottom of View:

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

&lt;script type=&quot;text/javascript&quot;&gt;
    $(document).ready(function () {
    $(&#39;#agency&#39;).attr(&#39;disabled&#39;, true);
    $(&#39;#officer&#39;).attr(&#39;disabled&#39;, true);
    LoadAgencies();
});

function LoadAgencies() {
    $(&#39;#agency&#39;).empty();

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

function LoadOfficers(agencyId) {
    $(&#39;#officer&#39;).empty();

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

}


.cs for the View:

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&lt;City&gt; DisplayCityData { get; set; }
public IEnumerable&lt;County&gt; DisplayPIAddressCountyData { get; set; }
public IEnumerable&lt;Ethnicity&gt; DisplayPIEthnicityData { get; set; }
public IEnumerable&lt;ArrestMethod&gt; DisplayArrestMethodData { get; set; }
public IEnumerable&lt;Test&gt; DisplayTestGivenData { get; set; }
public IEnumerable&lt;Charge&gt; DisplayChargeData { get; set; }
public IEnumerable&lt;DrinkLocation&gt; DisplayLastDrinkData { get; set; }
public IEnumerable&lt;DrugRecognitionExpert&gt; DisplayDrugExpertData { get; set; }

public async Task OnGet()
{
    await _db.City.Select(a =&gt; a.CityName).ToListAsync();
    DisplayCityData = await _db.City.ToListAsync();
    await _db.County.Select(a =&gt; a.CountyName).ToListAsync();
    DisplayPIAddressCountyData = await _db.County.ToListAsync();
    await _db.Ethnicity.Select(a =&gt; a.EthnicityName).ToListAsync();
    DisplayPIEthnicityData = await _db.Ethnicity.ToList
英文:

I've been following a tutorial on how to have one dropdown cascade from another, but am unable to get it to work. Any assistance would be greatly appreciated. I do not know javascript well, so fudging my way thru. I am not entirely sure I have the URL portion correct?

I am attempting to populate the ArrestDept dropdown and then filter and populate the ArrestOfficer dropdown based on the selected ArrestDept.

Here is what I have so far:

Relevant Part of View:

                &lt;td style=&quot;width: 20%&quot;&gt;
                        &lt;div class=&quot;mb-3&quot;&gt;
                            &lt;label asp-for=&quot;Incident.ArrestDept&quot;&gt;&lt;/label&gt;
                            &lt;select id=&quot;agency&quot; class=&quot;form-select&quot;&gt;&lt;/select&gt;
                        &lt;/div&gt;
                &lt;/td&gt;
                &lt;td style=&quot;width: 20%&quot;&gt;
                    &lt;div class=&quot;mb-3&quot;&gt;
                        &lt;label asp-for=&quot;Incident.ArrestOfficer&quot;&gt;&lt;/label&gt;
                        &lt;select id=&quot;officer&quot; class=&quot;form-select&quot;&gt;&lt;/select&gt;
                    &lt;/div&gt;
                &lt;/td&gt;

@section Scripts at bottom of View:

@section Scripts
{
    &lt;partial name=&quot;_ValidationScriptsPartial&quot; /&gt;

    &lt;script type=&quot;text/javascript&quot;&gt;
        $(document).ready(function () {
        $(&#39;#agency&#39;).attr(&#39;disabled&#39;, true);
        $(&#39;#officer&#39;).attr(&#39;disabled&#39;, true);
        LoadAgencies();
    });

    function LoadAgencies() {
        $(&#39;#agency&#39;).empty();

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

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

    }

.cs for the View:

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&lt;City&gt; DisplayCityData { get; set; }
    public IEnumerable&lt;County&gt; DisplayPIAddressCountyData { get; set; }
    public IEnumerable&lt;Ethnicity&gt; DisplayPIEthnicityData { get; set; }
    public IEnumerable&lt;ArrestMethod&gt; DisplayArrestMethodData { get; set; }
    public IEnumerable&lt;Test&gt; DisplayTestGivenData { get; set; }
    public IEnumerable&lt;Charge&gt; DisplayChargeData { get; set; }
    public IEnumerable&lt;DrinkLocation&gt; DisplayLastDrinkData { get; set; }
    public IEnumerable&lt;DrugRecognitionExpert&gt; DisplayDrugExpertData { get; set; }

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

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

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


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

}

Relevant part of Incident Model:

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

Relevant part of Agency Model:

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

Relevant Part of Officer Model:

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

***An additional question is if this would be easier to accomplish using ONE table as I can easily combine the Officer and Agency models into ONE table. Actually, this would be my preference, but have not been able to find a tutorial that addresses how to do this.

I'm thinking I could easily eliminate the Agency model and simply combine them on the Officer model, so have edited to add the Agency to the Officer model. There could be many officers to a single 'OfficerAgency'.

using System.ComponentModel.DataAnnotations;

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

How would this change the code? Hoping it would make it simpler?

Just not sure how I would change the .cs to work on the single table, specifically the OnGetGetOfficers(int id):

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

    public JsonResult OnGetGetOfficers(int id)
    {
        var officers = _db.Officer.Where(x =&gt; x.OfficerAgency == id).OrderBy(x =&gt; x.OfficerDisplayName).ToList();
        return new JsonResult(officers);
    }

答案1

得分: 0

你的JS代码中存在多个问题:

  1. LoadAgencies 函数中,你多加了一个 }

  2. LoadOfficers 函数中,你漏掉了一个 }

  3. 每次使用 append 方法时,你都在新的一行写入字符串,你需要在JavaScript中使用 + 操作符来连接字符串,像下面这样(仅为例子,你的JS代码中有很多这种问题):

    $('#agency').append(''+
        '<option>---选择逮捕机构---</option>');
    

    或者将它们移到同一行:

    $('#agency').append('<option>---选择逮捕机构---</option>');
    
  4. 响应数据采用驼峰命名法,例如,你需要将 data.AgencyName 改为 data.agencyName

    $('#agency').append('<option value=' + data.id + '>' + data.agencyName + '</option>');
    
  5. Razor Pages 的路由不同于MVC,Razor Pages 使用 OnGetOnPost 处理Http Get和Post请求。URL与PageModelName和文件夹名称相关,例如:在 Pages/Student 文件夹中的 IndexModel,URL是:/Student/Index。如果它只在 Pages 文件夹中,URL 是:/Index。如果你需要在当前PageModel中定义另一个 GetPost 方法,你需要像这样定义方法名:OnGetHandlerName 或 OnPostHandlerName。URL是:/FolderName/PageModelName?handler=HandlerName

英文:

Your js contains multiple problems here:

1.You add an extra } in LoadAgencies function.

2.You miss a } in LoadOfficers function.

3.You can see each time you use append, the string in this method you always write in a new line, you need concatenate strings in JavaScript using the + operator like below(just an example, your js contains many this type problems):

$(&#39;#agency&#39;).append(&#39;&#39;+
    &#39;&lt;option&gt;---Select Arresting Agency---&lt;/option&gt;&#39;);

Or just move to the same line:

$(&#39;#agency&#39;).append(&#39;&lt;option&gt;---Select Arresting Agency---&lt;/option&gt;&#39;);

4.The response data is camel case format, for example, you need change data.AgencyName to data.agencyName:

$(&#39;#agency&#39;).append(&#39;&lt;option value=&#39; + data.id + &#39;&gt;&#39; + data.agencyName + &#39;&lt;/option&gt;&#39;);

5.Razor Pages routing is not like MVC, Razor pages uses OnGet and OnPost to deal with the Http Get and Post request. And the url is related to the PageModelName and folder name, e.g: IndexModel in Pages/Student folder, the url is:/Student/Index. If it is just in Pages folder, the url is:/Index. If you need another Get or Post method in current PageModel, you need define the method name like: OnGetHandlerName or OnPostHandlerName. The url is: /FolderName/PageModelName?handler=HandlerName.


Whole working code:

Page

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

JS in page:

@section Scripts
    {
    &lt;partial name=&quot;_ValidationScriptsPartial&quot; /&gt;

    &lt;script type=&quot;text/javascript&quot;&gt;
            $(document).ready(function () {
            $(&#39;#agency&#39;).attr(&#39;disabled&#39;, true);
            $(&#39;#officer&#39;).attr(&#39;disabled&#39;, true);
            LoadAgencies();
        });

        function LoadAgencies() {
            $(&#39;#agency&#39;).empty();

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

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

}

PageModel

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

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

huangapple
  • 本文由 发表于 2023年2月13日 23:05:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定