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

下拉框选值时AJAX传空值至控制器,需实现选值触发数据库取数

Hey there! Let's fix those two issues you're facing—getting null values in your controller via AJAX when selecting a dropdown option, and properly fetching data from the database based on that selection. Here's a complete, working solution:

Fixing AJAX Null Value Issue & Dropdown-Driven Data Fetch

1. Why You're Getting Null Values

Common culprits behind this problem are:

  • Mismatched parameter names between your AJAX request and controller action
  • Incorrect data formatting in the AJAX call
  • Forgetting to align HTTP methods (GET/POST) between AJAX and the controller

2. Complete Working Code

Razor View (CSHTML)

Your existing dropdown is close—here's the refined version with context on initial setup:

@* Populate dropdown options via ViewBag in your controller's GET action *@
@Html.DropDownList("Code", ViewBag.CodeOptions as SelectList, "Select an Option", 
    htmlAttributes: new { @class = "form-control", @onchange = "fetchData(this.value)" })

@* Add a container to display fetched data *@
<div id="dataContainer" class="mt-3"></div>

JavaScript/AJAX Function

This corrected function ensures the selected value is sent properly to your controller:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function fetchData(selectedCode) {
    // Skip if no valid option is selected
    if (!selectedCode) {
        alert("Please select an option first!");
        return;
    }

    $.ajax({
        url: '/YourController/GetDataByCode', // Replace with your actual controller/action path
        type: 'GET', // Match this to your controller's [HttpGet]/[HttpPost] attribute
        data: { code: selectedCode }, // Key name must match controller parameter name
        success: function(response) {
            // Update the UI with fetched data (customize this as needed)
            $('#dataContainer').html(`
                <h5>Fetched Data:</h5>
                <pre>${JSON.stringify(response, null, 2)}</pre>
            `);
        },
        error: function(xhr, status, error) {
            console.error("Error fetching data:", error);
            alert("Failed to load data. Please try again.");
        }
    });
}
</script>

Controller Action

Here's the controller code to receive the dropdown value and fetch data from your database:

using Microsoft.AspNetCore.Mvc;
using YourDataAccessLayer; // Replace with your DB context namespace

public class YourController : Controller
{
    private readonly YourDbContext _dbContext;

    // Inject your DbContext via constructor dependency injection
    public YourController(YourDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    // Action to load initial page and dropdown options
    public IActionResult Index()
    {
        // Populate dropdown options from database
        var codeOptions = _dbContext.YourEntity
                            .Select(e => new SelectListItem
                            {
                                Text = e.CodeDisplayName, // Replace with your display field
                                Value = e.Code // Replace with your value field
                            }).ToList();

        ViewBag.CodeOptions = codeOptions;
        return View();
    }

    // Action to handle AJAX request and return database data
    [HttpGet]
    public IActionResult GetDataByCode(string code)
    {
        if (string.IsNullOrEmpty(code))
        {
            return BadRequest("Code cannot be null or empty.");
        }

        // Fetch data from database using the selected code
        var fetchedData = _dbContext.YourEntity
                                    .Where(e => e.Code == code)
                                    .ToList(); // Adjust query to match your entity needs

        return Json(fetchedData); // Return data as JSON to AJAX call
    }
}

3. Critical Fixes to Avoid Null Values

  • Parameter Name Matching: Ensure the data key in AJAX (code) exactly matches the controller action's parameter name (string code)—case sensitivity matters!
  • Validate Selected Value: The JS check prevents sending empty values when the default "Select an Option" is chosen.
  • Align HTTP Methods: If you use [HttpPost] in your controller, update the AJAX type to POST and add contentType: 'application/json' (then stringify the data: data: JSON.stringify({ code: selectedCode })).

4. Testing the Solution

  1. Run your app and select an option from the dropdown.
  2. Open browser dev tools (F12) → Network tab to verify the request sends the selected code.
  3. Set a breakpoint in the GetDataByCode action to confirm the controller receives the value correctly.
  4. Check the response in the Network tab to ensure database data is returned and displayed in the UI.

内容的提问来源于stack exchange,提问作者Alishah momin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:11:15