You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC中AJAX级联下拉列表无法填充数据求助

Troubleshooting Your AJAX Cascading Dropdown Issue

Let's walk through why your series dropdown isn't populating with data beyond "Make Selection" and fix it step by step:

1. Fix AJAX dataType Case Sensitivity

First, JavaScript is case-sensitive, and you've written datatype instead of the correct dataType in your AJAX call. This can prevent jQuery from properly parsing the JSON response, meaning your success function might not process the returned data at all.

Here's the corrected AJAX script, plus added error handling to help debug issues:

$(document).ready(function () {
    $('#ProductLineID').change(function () {
        $.ajax({
            url: '/SMRMaster/RequestForm/GetSeries',
            type: 'GET',
            dataType: 'JSON', // Fixed case here
            data: { id: $('#ProductLineID').val() },
            success: function (result) {
                $('#SeriesID').empty(); // Cleaner than .html('')
                $('#SeriesID').append('<option>Make Selection</option>');
                $.each(result, function (index, item) {
                    // Use .text() instead of .html() for safer content rendering
                    $('#SeriesID').append($('<option></option>').val(item.Value).text(item.Text));
                });
            },
            error: function(xhr, status, error) {
                // Log errors to browser console for debugging
                console.log("AJAX Request Error: " + error);
                console.log("Server Response: " + xhr.responseText);
            }
        });
    });
});

2. Correct Backend Series Query Logic

Looking at your GetSeries controller method, there's a critical issue in how you're building the SelectListItem objects: you're setting both Value and Text to s.ProductLineName. That means every option would just repeat the product line name, not the actual series data!

You need to map to the correct fields from your Series table (adjust SeriesId and SeriesName to match your actual database schema):

public JsonResult GetSeries(string id)
{
    // Add validation to handle invalid ID inputs
    if (!int.TryParse(id, out int productLineId))
    {
        return Json(new List<SelectListItem>(), JsonRequestBehavior.AllowGet);
    }

    db.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
    
    // Use switch expression for cleaner code
    string productLineName = productLineId switch
    {
        0 => "Electric",
        1 => "Europe Gas",
        2 => "Gas",
        3 => "Miscellaneous",
        4 => "Water",
        _ => "Electric"
    };

    // Map to the correct Series fields (adjust to your actual columns)
    IEnumerable<SelectListItem> series = (from s in db.Series
                                         where s.ProductLineName == productLineName
                                         select new SelectListItem
                                         {
                                             Value = s.SeriesId.ToString(), // Unique ID for the series
                                             Text = s.SeriesName // Human-readable series name
                                         }).ToList();

    return Json(series, JsonRequestBehavior.AllowGet);
}

3. Debugging Steps to Verify

If the fixes above don't resolve the issue, use these steps to narrow it down:

  • Open your browser's DevTools (F12) and go to the Network tab. Select the GetSeries request and check:
    • Status Code: Should be 200 (OK). If it's 404, double-check your AJAX url path matches the controller/action route. If it's 500, look at the server response for exception details.
    • Response: Verify the JSON returned contains valid Value and Text properties for each series.
  • Add a breakpoint in your GetSeries controller method to confirm it's being called with the correct id value, and that the LINQ query is returning the expected series data.

4. Quick View Model Consistency Check

Your RequestViewModel has a List<Series> property, but since you're returning SelectListItems from the AJAX call, this doesn't cause an issue—just make sure your frontend is only relying on the AJAX-populated dropdown, not the view model's Series list (which isn't being populated in the RequestForm action).

内容的提问来源于stack exchange,提问作者Chase Koch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:05:51