Ajax requests with MVC action methods that lack parameters may fail to return any results

I have 2 dropdown list boxes where I load values into the first dropdown list and based on its selection, I load values into the second dropdown list using the same action method through ajax.

Here is the script I am using:

$(document).ready(function () {       
    $("#ddlOrgs").change(function () {
    var listSite = $("#_site");
    var SelctedOrgCode = $("#ddlOrgs").val();
    alert(SelctedOrgCode);
    if (SelctedOrgCode != 0) {               

        var url = '@Url.Action("GetSites","FilterMenu")';               
        $.ajax({               
            url : url,
            type: 'POST',
            tempdata:{},
            data: JSON.stringify(tempdata),                    
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
        })
        .done(function (data) {   
        var sitesDropdown = $("#ddlSites");                                      
        var list = data;
        $.each(list, function (index, item) {
                sitesDropdown.append('<option value?+item.SiteCode+?="">' + item.SiteName + '</option>');
                alert(item);
         });

      })
      .fail(function(xhr){
           alert('failed');
           alert(xhr.responseText); 
     });
            }             
        });
    });

The Controller action methods are as follows:

[HttpPost]
public IEnumerable<Client> LoadFiltersX(constants.ClientType clientType)
{  
    // Code here
}

[HttpPost]              
public JsonResult GetSites()
{             
    return Json( LoadFiltersX(constants.ClientType.SITE), JsonRequestBehavior.AllowGet);
}

In my repository, I return a List collection like this:

public List<Client> GetClientInformation(constants.ClientType clientType)
{
    // Code here
}

The view part in the Layout file looks like this:

@if (Session.Count > 0 && Session["UserName"].ToString().Length > 0)
{
    // Code here
}

When calling, no results are returned and the console displays an error "tempdata undefined". The method does not pass any parameters. Each dropdown list has the same client list but the first takes 'ORG' enum and the second takes 'SITE' enum. So I passed it for each method. I want to get the list to populate the dropdown list. I can successfully load the first dropdown list via a normal Action method in the Controller, but the problem occurs in the ajax method. Can anyone help me with this issue? Thank you in advance.

Thank you, tpk

Answer №1

Make sure to eliminate the "tempdata" variable from your ajax call if it isn't required.

        $.ajax({               
            url : url,
            type: 'POST',                
            data: {}, // Provide the parameters for the MVC action method here...                    
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
        })

url = '@Url.Action("GetSites","FilterMenu")'; : Remember, this might not function properly if you relocate your JavaScript to a separate file. Use a relative URL "/Controller/ActionMethod".

Answer №2

I managed to find the solution by utilizing $.getJSON with JsonResult Return method

  var url = "/FilterMenu/GetAllSites"
  $.getJSON(url, function (response) {           
            sites.empty(); // remove any existing options
            $.each(response, function (index, item) {         
                sites.append('<option value='+item.SiteCode +'>' + item.SiteName + '</option>')
            });

Indeed, you were right that I initially used the @Url.Action method but encountered an error indicating "cannot find location 404 error" when clicking on the link. The URL loaded in the browser as follows: (this led to another issue) http://localhost:10345/Home/FilterMenu/GetAllSites (note a new link is added to the Home Controller part)

By providing the full URL (like 'http://localhost:10345/FilterMenu/GetAllSites') and hitting enter, it directed me to the correct action method and returned results.

I came to realize that the additional /Home part was causing the error. I have now switched to using a relative URL as you suggested, which resolved the issue. Interestingly, I had previously tried the same approach without success, but utilizing $getJSON this time around proved to be effective. Thank you for your response and assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to style text alignment and create a toggle button using HTML and CSS

My attempt at creating a custom toggle button using an HTML input checkbox and custom CSS has resulted in a misalignment between the text and the toggle button itself. Despite my efforts to adjust margins, padding, and heights, I have been unable to resolv ...

Troubleshooting a unique CSS bug in jQuery mouseover functionality

Check out this pen: https://codepen.io/anon/pen/eKzEVX?editors=1111 I recently created a Form Select in Laravel: {!! Form::select('status_id', $statuses, $post->status_id, ['class' => 'form-control post-sub-items-label &apo ...

The Bootstrap Hugo Documentation website is experiencing difficulties and displaying the error message "failure to render 'page'"

Currently, I have bootstraps' source code downloaded on my Mac along with all the necessary node packages installed. Upon attempting to run hugo --cleanDestinationDir --printUnusedTemplates (hugo is properly installed), I encountered the following err ...

Attributes requested with jQuery JavaScript Library

Is there a way to dynamically add extra key-value pairs to the query string for all requests sent to the web server? Whether it's through direct href links, Ajax get post calls or any other method, is there a generic client-side handler that can handl ...

"Step-by-step guide to building a webgrid or table to organize and display your

These are the HTML codes I have created: <table> <tr> <td><label style="text-align:left">Product Code:</label></td> <td><input type="text" id="productCode" value="" /> </td> </tr> & ...

Guide to dynamically updating the href of an SVG Image in Angular HTML

I am currently iterating through a list of employee objects, each containing an image URL that I need to incorporate into an SVG - Image element. <div *ngFor ="emp of employees"> <defs> <pattern id = "attachedImage" height ...

Transform HTML into PNG with Canvas2image, followed by the conversion of PNG into BMP

Is there a direct way to convert HTML to BMP? After searching online, it seems that there isn't a straightforward method. So, I decided to convert HTML to PNG using canvas JS and then use PHP to convert the file from PNG to BMP. I have a question abou ...

Leveraging JavaScript within a Polymer component

I have an object made with polymer: <newfolder-element id="newfolderelement" popupStyle="width: 362px; height: 100px;"> <span class="title">Create a new folder</span> <input type="text" class="ginput" style="width: 350px; padd ...

Tips for selecting a title bar in a custom jqgrid

I need to display a message in just one of the multiple grids on my screen. However, the current code I am using attaches the message to all the grids. $(".ui-jqgrid-titlebar").append("<span>Error Message</span>"); Is there a way for me to ta ...

An element generated using a JavaScript loop is covering another element in the layout

I am facing an issue with positioning images within a div to a span. The problem arises as the images are overlapping each other and I am uncertain about how to properly place each image when it is added. Below is the code snippet: The CSS: <style ty ...

Neither the view nor the controller are being properly loaded into the index.html file

I initially had my angular app loading my javascript correctly, but the routing was not properly set up. I am currently trying to resolve this issue, but now my javascript alert is not even popping up, indicating that the file is not connected. Can anyone ...

Issue with Bootstrap4 card alignment on Chrome browser

Hey there! I could use some assistance with an issue I'm facing in Bootstrap4 cards while using Chrome. The strange thing is that everything seems to be working fine on IE11, but not on Chrome. Take a look at the comparison images below: IE11 layout ...

Performing multiple ajax calls simultaneously in JavaScript using the React framework

Within my React application, I am faced with the challenge of handling an array of parameters (such as IDs) that need to be passed as parameters in a queue of ajax calls. The issue arises when this array exceeds 1000 items, causing the browser page to beco ...

having trouble reaching the jQuery Object inside a plugin

It may seem like a small issue, but I'm having trouble with the following function in my plugin. Despite my efforts, nothing seems to be working and I can't even get an alert. Any ideas on what might be causing this problem? (function($){ $.f ...

Navigating through the settings menu by using a web browser

Can device settings be accessed from a mobile browser using HTML5 and JavaScript? I am attempting to replicate a feature found in Android, where you can launch an intent to display a specific settings page using code like the example below. Intent intent ...

Content submission and updates, modeled after the Twitter platform

Hello there. I am currently working on a quotation service and ran into an issue while attempting to implement twitter-like data submission and display: all of my ajax requests seem to be executed twice. I am using jQuery in the following manner: I hav ...

Using the device's width and height with material-ui

Currently, I am attempting to specify the width and height for only the (Iphone 7 Plus) within my project using withStyles. import { withStyles } from "@material-ui/core"; I have tested the following code: "@media (width: 414px) and (height ...

Ensure that the text inside the button does not exceed its boundaries (utilizing Bootstrap v4)

My current code snippet appears below. <div class="col-xl-2 col-lg-12"> <button class="btn btn-secondary w-100" value=1>But.</button> </div> <div class="col-xl-4 col-lg-12"> <button cla ...

When utilizing a script to deliver a true or false response for jQuery's .load() function

Currently, I have found myself delving deep into jquery to manage the ajax requests in my web applications. Specifically, I am working on a bidding system in PHP that heavily relies on mod_rewrite. Using jQuery with a confirm dialog, I send an Ajax request ...

What is the reasoning behind jQuery UI employing CSS classes as opposed to pseudo-classes?

In this detailed explanation found on this website, it is discussed why jQuery UI uses CSS classes like .ui-state-active that are applied through JavaScript, rather than utilizing existing CSS pseudo-classes like :active. What is the reasoning behind thi ...