@onchange中调用Ajax报"url undefined"错误求助
Hey there, let's tackle that "url undefined" error you're hitting when trying to populate the child dropdown via Ajax. The most common culprit here is hardcoding the URL in your JavaScript, which can break if your app is deployed under a subdirectory or if your MVC routing setup changes. Let's walk through the fixes step by step.
First: Understand the Root Cause
When you use a hardcoded URL like /QueueBuilder/GetDepartmentsByClient, it assumes your app is hosted at the root of the domain. If it's not, or if your MVC routing has custom settings, this path won't resolve correctly—leading to the "url undefined" (or a hidden 404 error under the hood). Instead, we should let ASP.NET MVC generate the correct URL for us using Url.Action().
Solution 1: Pass the Correct URL to Your JavaScript Function
Modify your dropdown's onchange attribute to pass the properly generated URL directly to the ClientChange function:
@Html.DropDownList("queueclientDropdownList", new SelectList(Model.Clients, "Id", "Name"), "Select Client", new { ng_model = "queueclientDropdownList", ng_required = "false", ng_value = "false", @class = "form-control", @onchange = $"ClientChange('{Url.Action("GetDepartmentsByClient", "QueueBuilder")}')" })
Then update your JavaScript function to accept and use this URL:
function ClientChange(url) { var clientId = $('#queueclientDropdownList').val(); $.ajax({ url: url, type: "POST", dataType: "JSON", data: { clientId: clientId }, success: function (data) { $("#queuedepartmentDropdownList").empty(); $("#queuedepartmentDropdownList").append($('<option></option>').val(0).html("Select Department")); $.each(data, function (i, department) { $("#queuedepartmentDropdownList").append($('<option></option>').val(department.Id).html(department.Name)); }); } }); return true; }
Solution 2: Define a Global URL Variable (Alternative Approach)
If you prefer not to pass the URL as a parameter, you can define a global variable in your Razor view that holds the correct URL, then reference it in your JavaScript:
Add this script block somewhere in your .cshtml file (before your ClientChange function):
<script> // Let MVC generate the correct URL for us var getDepartmentsUrl = '@Url.Action("GetDepartmentsByClient", "QueueBuilder")'; </script>
Then update your Ajax call to use this variable, plus add an error handler for easier debugging:
function ClientChange() { var clientId = $('#queueclientDropdownList').val(); $.ajax({ url: getDepartmentsUrl, // Use the global variable here type: "POST", dataType: "JSON", data: { clientId: clientId }, success: function (data) { $("#queuedepartmentDropdownList").empty(); $("#queuedepartmentDropdownList").append($('<option></option>').val(0).html("Select Department")); $.each(data, function (i, department) { $("#queuedepartmentDropdownList").append($('<option></option>').val(department.Id).html(department.Name)); }); }, // Optional: Debug failed requests error: function(xhr, status, error) { console.log("Request Error:", error); console.log("Status Code:", status); } }); return true; }
Additional Checks to Make
- Verify Your Controller Action: Ensure your
QueueBuilderControllerhas theGetDepartmentsByClientaction, and it's decorated with[HttpPost](since your Ajax call usestype: "POST"):[HttpPost] public JsonResult GetDepartmentsByClient(int clientId) { // Your logic to fetch departments by clientId here var departments = // ... retrieve data from your service/repository return Json(departments); } - Check jQuery is Loaded: Make sure you've included jQuery in your page before your
ClientChangefunction runs. A missing jQuery reference would cause$to be undefined, which can lead to related errors. - AngularJS vs jQuery Conflict: You're using AngularJS directives (
ng_model, etc.) but fetching values with jQuery. While this isn't the direct cause of the URL error, mixing frameworks can lead to unexpected behavior. If you're using Angular, consider using Angular's$httpservice instead of jQuery's Ajax for consistency.
内容的提问来源于stack exchange,提问作者karthisena

