简体   繁体   English

获取Ajax调用未达到控制器操作

[英]Get Ajax call not hitting controller action

I have been struggling to get this Get request to hit the url. 我一直在努力获取此Get请求以击中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. 我试着在一个单独的js文件中手动输入url参数,然后再将所有js移至cshtml以方便剃刀。 Still getting a 404 error on the request. 在请求上仍然出现404错误。 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. 您不能在.js文件中使用@Url.Action() You could manually setup the URL like: 您可以手动设置URL,例如:

$.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 用于当前控制器请求之外的内容(请注意, ../是使URL与当前MVC视图相对)或仅

$.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.Action用于视图中而不是JS文件中,则无需指定单词“ 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. 遗憾的是,为了将来参考,我不是100%的原因,也许有人可以添加这个答案。 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. 但是我最初将其设置为Web API控制器,但经过反复试验,最终导致重新创建控制器,而创建了常规MVC控制器。 I copy and pasted my code into the controller and was able to hit the URL. 我将代码复制并粘贴到控制器中,并能够访问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: 和Ajax调用:

    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. 但是,此代码在Web Api控制器中对我不起作用,如果有人想补充为什么会这样,我很想听听您的反馈,但我也会自己做一些研究。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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