简体   繁体   中英

Get Ajax call not hitting controller action

I have been struggling to get this Get request to hit the url. I tried entering the url parameter manually in a separate js file, before moving all my js to cshtml to give razor a go. Still getting a 404 error on the request. Any and all help is much appreciated as I am newer at this.

function ShowMarketingMaterial() {

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

Here 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.Services.WebMethod]

        [System.Web.Http.HttpGet]
        //[System.Web.Http.Route("{GetMarketingMaterial}")]

        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);
        }
    }
}

You can't use @Url.Action() inside a .js file. You could manually setup the URL like:

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

for outside the current controller request (Note that the ../ is to make the URL relative from the current MVC view) or just simply

$.ajax({
    url: 'GetMarketingMaterial'

for a request to an action method inside the same controller that is serving the current view.

Also just to note that Url.Action, if used in a view and NOT in a JS file, you don't need to specify the word "controller".

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

Please check url in console. You may have problem with url use

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

i think your "" creating issue. Hope this will help

I figured this out last night. Sadly for future reference, I am not 100% on the cause, maybe someone can add to this answer. But I originally set it up as a Web API Controller, and by trial and error came down to recreating the controller and instead, created a regular MVC controller. I copy and pasted my code into the controller and was able to hit the URL. I add a few minor changes to the code, and namespaces.

Here is the new 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);
        }
    }
}

and the Ajax call:

    function ShowMarketingMaterial() {

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

}

Mind you, this code is not exactly identical to the original post, as many changes were made for trying to get this to work. However, this code wouldn't work for me in the Web Api controller, if anyone would like to add to why this might be, I would love to hear your feedback, but I will also do some research of my own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM