Unable to reach controller action with Ajax request

I've been encountering issues trying to make a Get request to hit the specified URL. Initially, I attempted inputting the URL parameter manually in a separate JS file, then transitioning all my JS to cshtml to test out Razor. However, I am still facing a 404 error when making the request. Any assistance or guidance would be greatly appreciated, especially since I am relatively new to this.

function ShowMarketingMaterial() {

$.ajax({
    url: "@Url.Action("GetMarketingMaterial", "MarketingMaterialController")",
    type: "GET",
    data: option,
    dataType: 'json',
    success: OnSuccess,
    failure: function (response) {
        alert(response.d);
    }
});

Below is my controller:

using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using WebApplication2.Data;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class MarketingMaterialController : ApiController
    {
        private ImprevDBEntities db = new ImprevDBEntities();
        
        [System.Web.Http.HttpGet]
        
        public IHttpActionResult GetMarketingMaterial(string test)
        {
            var test1 = from M in db.DimMarketingMaterials
                        join I in db.DimListingIdentifiers on M.ListingId equals I.ListingId
                        where M.Url.StartsWith("https://client.marketing.imprev.net/")
                        && I.ListingNumber == test
                        select new MarketingMaterial
                        {
                            UrlMaterial = M.Url,
                            Description = M.Description
                        };

            var response = new MarketingMaterialsViewModel();
            response.MarketingMaterials = new List<MarketingMaterial>();
            response.MarketingMaterials = test1.ToList();

            return Ok(response);
        }
    }
}

Answer №1

It is not possible to utilize @Url.Action() within a .js file. You can manually define the URL like this:

$.ajax({
    url: '../MarketingMaterial/GetMarketingMaterial'

if it is outside of the current controller request (Note that the ../ is used to specify the URL as relative from the current MVC view) or simply use

$.ajax({
    url: 'GetMarketingMaterial'

for a request to an action method within the same controller serving the current view.

Additionally, if you use Url.Action in a view and NOT in a JS file, there is no need to include the word "controller".

url: '@Url.Action("GetMarketingMaterial", "MarketingMaterial")',

Answer №2

Make sure to verify the URL in the console. There could be a problem with the URL being used.

'@Url.Action("GetMarketingMaterial", "MarketingMaterialController")'

It seems like your quotes may be causing some issues. Hopefully this information will assist you.

Answer №3

Last night, I finally managed to figure this out on my own. While I'm not entirely sure of the root cause, I hope that someone can contribute further insights to this solution. Originally, I set it up as a Web API Controller, but through trial and error, I ended up recreating the controller as a regular MVC controller. I simply copied and pasted my existing code into the new controller and was able to access the URL successfully after making some minor adjustments to the code and namespaces.

Below is the updated working Controller:

namespace WebApplication2.Controllers
{
    [RoutePrefix("api/MarketingMaterial")]
    public class TestController : Controller
    {
        private ImprevDBEntities db = new ImprevDBEntities();

        // GET: Test
        [HttpGet]
        [Route("GetMarketingMaterials/{option}")]
        public ActionResult Index(string option)
        {
            var test1 = from M in db.DimMarketingMaterials
                        join I in db.DimListingIdentifiers on M.ListingId equals 
                        I.ListingId
                        where 
                        M.Url.StartsWith("https://client.marketing.imprev.net/")
                        && I.ListingNumber == option
                        select new MarketingMaterial
                        {
                            UrlMaterial = M.Url,
                            Description = M.Description
                        };


            var response = new MarketingMaterialsViewModel();
            response.MarketingMaterials = new List<MarketingMaterial>();
            response.MarketingMaterials = test1.ToList();

            return Json(response, JsonRequestBehavior.AllowGet);
        }
    }
}

Additionally, here's the Ajax call made:

function ShowMarketingMaterial() {

    $.ajax({
        url: '/api/MarketingMaterial/GetMarketingMaterials/' + option,
        type: 'GET',
        dataType: 'json',
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        }
    });

}

Please note that while this code may have undergone several modifications from the original post in order to make it functional, the main issue for me was resolved by switching to a MVC controller instead of using a Web Api controller. If anyone has any theories or explanations as to why this change was necessary, I would greatly appreciate your input. Nevertheless, I will also continue researching this matter on my own.

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

Save the contents of a file within an HTML table using jQuery

I needed to insert multiple files into the database by uploading and adding each file's content to a table. Once all files were added to the table, I included the table's values along with the file content in form data which was then passed to aj ...

Node-powered Angular

Currently working on setting up client-side routing with AngularJS and Node. Ran into some issues along the way. EDIT After making changes to my code based on recommendations from @PareshGami, following https://github.com/scotch-io/starter-node-angular, I ...

Shifting the pagination outside of the slider in ReactJS and SwiperJS seems to be tricky. Despite trying to adjust the margins and padding, the pagination

I've been struggling with this issue for a while now. I need to move the pagination outside of the slider, but using padding or margin doesn't seem to work. It always remains inside the slider, and if I try to position it outside, it gets hidden. ...

Using the Unsigned Right Shift Operator in PHP (Similar to Java/JavaScript's >>> Operator)

Before marking this as a duplicate, please take a moment to read the information below and review my code * my updated code! The issue I am facing is that I need to implement Java/JavaScript '>>>' (Unsigned Right Shift / Zero-fill Right Shift) ...

A method for extracting URL parameters based on the matching route path

Is it possible to parse a given URL string in relation to the match.path value? For instance, if the current route is: <Route path="/some/path/:type" /> To obtain the type parameter of the current URL, one can simply use match.params.type ...

Utilize a standard JavaScript function from a separate document within a function of a React component

I am facing an issue where I need to incorporate a standard JavaScript function within a React component function. The script tags are arranged in the footer in the following order: <script src="NORMAL JAVASCRIPT STUFF"></script> // function ...

ERROR: Module 're2' not found in './build/Release/re2' (npm)

After receiving suggestions from sonarQube, I am attempting to switch out my original regular expression with RE2. However, upon installation, the following error message appears: Error: Cannot locate module './build/Release/re2' Important note ...

The Google Maps API allows all markers to be connected to a single infowindow

I've been grappling with this issue for some time now, but I just can't seem to find a solution! I'm retrieving data from a database in Laravel using Ajax and then attempting to display infowindows for each marker on Google Maps. The markers ...

What is the maximum number of JSON responses that can be handled by AJAX?

Upon entering the site, I am attempting to receive a JSON as an AJAX response. However, I am curious if there is a limit to the size of the object I can retrieve - whether through a GET or POST request? $http({ method: 'POST', url: &apos ...

Tips for displaying a div only when the input value is greater than 0, and hiding it when the value is 0

My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try. Here is my initial attempt: var input = document.getElementById( ...

Tips for initiating a jQuery form submission

At this moment, the form is being submitted using the default URL. I would like it to utilize the form submit event in my JavaScript code so that it can pass the .ajaxSubmit() options. Below is the corresponding JavaScript code: $('#selectedFile&a ...

Using LINQ to group and organize data to generate a series for a chart

Consider a simplified Items entity, which includes the following properties: Id (int, PK), itemDate (datetime, not null), and itemCategory (string, not null). Can you provide a LINQ to Entities query that calculates the total number of items in each categ ...

The functionality of Vue is acting up with the HTML, unexpectedly refreshing when a button is clicked

I am currently experiencing an issue with my Vue application. When I click the button, it clears the input field (which it shouldn't) and doesn't perform any other actions. The variables "codigo" and "payload" do not display anything on the scree ...

disable event listeners on the DOM

I am currently developing a web framework and focusing on integrating XSS prevention measures. I have successfully implemented data escaping for database storage, but now I am faced with the challenge of allowing users to save generated HTML without riskin ...

Excessive image display | HTML and CSS synergize

I am having some trouble with my image gallery. Each image is displayed as a vertical column and has zooming effects when hovered over. Clicking on an image should show it in full screen with a caption. The problem arises when dealing with images that are ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

Issue with date: date.toLocaleTimeString function is invalid

I'm currently working on creating a time display component using hooks, but I'm running into an issue with the error message "TypeError: date.toLocaleTimeString is not a function." As a newcomer to this technology, any guidance would be greatly a ...

What is the best way to integrate a PHP page with its own CSS and JavaScript into a Wordpress page?

I'm facing a challenge with integrating a dynamic PHP table into my WordPress page. Despite working perfectly when opened locally, the CSS and JavaScript used to create the table are not functioning properly when included in a WordPress page via short ...

Ways to retrieve a value within a function and update a variable

Fetching data from the firebase database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ console.log('Error!'); console.log(err); } function gotData(d ...

Once all ajax requests have been completed,

My task involves performing multiple ajax requests in order to populate select boxes and then hide the loading panel once everything is loaded. The process works perfectly when done in a specific way: $.when( $.getJSON(applicationUrl + "data/codiciPa ...