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

Generating hills with PlaneGeometry in Three.js

Currently, I am searching for a straightforward technique to generate non-uniform hills in Three.js. By utilizing particles and positioning them with a sine wave algorithm like the following snippet: x = Math.random() * 1000 y = Math.sin( x / freq ) * ...

Creating a Show/Hide toggle feature in AngularJS using NG-Repeat

I'm facing an issue with my code where I have a list of items that should only open one item at a time when clicked. However, currently, all items are opening on click and closing on the second click. Can anyone help me identify the problem in my code ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...

Troubleshooting the issue with reactdom.render() functionality in CodeSandbox

Having issues with ReactDom in CodeSandbox for React. The HTML file includes: <body> <div id="root"></div> </body> <script src="scr/index.js"> The JavaScript file (named index) includes: ReactDOM.rende ...

Transform the JSON object into a different JSON format

I am in the process of restructuring the JSON data which is currently organized by categories, with each category containing multiple locations. Each location consists of latitude/longitude coordinates and an area code: { "cat1":[ {"location":{ ...

Error: The specified function in the schema is not valid for the current operation mode

I'm facing an issue with validating a material ui form using Formik and Yup. The error keeps popping up. This is the schema I imported from another file: export const validationSchema = Yup.object({ email: Yup.string() .email('Invalid Ema ...

Prop validation error: prop type mismatch occurred

My Vue.js countdown isn't displaying the values correctly. Despite defining everything as numbers, I keep getting an error in the console: [Vue warn]: Invalid prop: type check failed for prop "date". Expected Number, got String. I've gone th ...

Animate the expansion and shrinkage of a div instantly using jQuery

I am trying to create an animation effect using jQuery animate on a div element where it starts large and then becomes smaller. Here is the code I have written: $(this).animate({ opacity: 0, top: "-=100", width: "38px", height: "32px" }, 1 ...

How do I use regex to grab all the text between two specific headers?

I need help extracting text between two specific headings. I attempted to create a regex for this purpose, but it's not quite capturing what I want. Currently, it includes the heading and paragraph, but misses the last heading. My Current Regex: /^& ...

Tips for incorporating conditional statements within return statements in functional components in React JS

I need to display the login page if the user is not logged in, otherwise show the forbidden 403 page. Since I'm using a functional component, I can't use render(). return forbidden === false ? ( <> <Container maxWidth="x ...

Error message: Unchecked runtime error - Unable to retrieve data from the specified URL. The extension manifest must include permission to access this particular host. This issue is occurring in manifest

Can someone help me out? I keep on receiving the error messages Unchecked runtime.lastError: Cannot access contents of url. Extension manifest must request permission to access this host. and Unchecked runtime.lastError: Could not establish connection. Rec ...

Using Vue.js to update the v-bind:style when the mouse hovers over the element

I am working with a span element that displays different background images based on certain conditions. Here is the HTML: <span v-if="type" :style="styles" > </span> In the computed properties section: ...

Execute a series of promises sequentially, ensuring that each subsequent promise is only run after the previous one has been resolved

I am in the process of creating a script that will execute all found .sql files within a designated folder one by one. The objective is to halt the execution if any one of the scripts fails. The structure of my folders is as follows (and I initiate the scr ...

Embrace the compatibility of both .NET 4.5 and DotNetCore

How do I go about enabling support for both .NET 4.5 and DotNetCore? Would creating a PCL (Portable Class Library) for shared code be the most effective approach to target DNX + .NET 4.5? I have a library that I distribute as a NuGet package with compati ...

Retrieve AJAX images but experiencing issues with jQuery click function

In the index HTML file, I have 7 images. I have implemented a jQuery function that gets the ids of the images when they are clicked. The jQuery function looks like this: $(".imgss").click(function() { alert($(this).attr("id")); }); I assign the clas ...

encountering the issue of not being able to assign a parameter of type 'string | undefined' to a parameter of type

Seeking help with the following issue: "Argument of type 'string | undefined' is not assignable to parameter of type" I am unsure how to resolve this error. Here is the section of code where it occurs: export interface IDropDown { l ...

What is the best way to create a scrollable tbody in an HTML table using React?

In my current project, I am using React, Node, Express, and Postgres to fetch data from a database. The issue I'm facing involves creating a scrollable table within a div that spans the entire screen width. Initially, I had to apply display: block to ...

What is the process for implementing document.ondrop with Firefox?

I'm experiencing an issue where the document.ondrop function seems to be working in Chrome, but not in Firefox. Here's a link to an example demonstrating the problem: In the example, if you try to drop a file onto the page, it should trigger an ...

find a solution for using a static method within a generic interface

In my business setup, I have a model called TaskItem. Through an API, I fetch data for these tasks known as taskitems. To handle this, I create a corresponding TaskItemModel for each controller, which I refer to as TaskItemDTO. The idea is for the TaskIte ...

Tips for avoiding an automatic slide up in a CSS menu

Is there a way to disable the automatic slide-up effect on my CSS menu when clicking a list item? I have tried using stop().slideup() function in my JavaScript code, but it doesn't seem to work. Additionally, I would like to highlight the selected lis ...