【问题标题】:Ajax call not reaching controller methodAjax 调用未到达控制器方法
【发布时间】:2015-05-26 02:12:13
【问题描述】:

是的,有很多帖子都有类似的问题。我尝试按照其中的答案进行操作,但我的 ajax 调用仍未到达控制器方法。

控制器(SalesController.cs):

[HttpGet]
public JsonResult fillVarietiesSelect(int species_id)
{
    String[] alist = {"a","b","c"};
    return Json(alist, JsonRequestBehavior.AllowGet);
}

javascript:

$('#species-select').on('change', function () {
    var species_id = $('#species-select').val();
    console.log("species id selected " + species_id);
    alert("species id selected " + species_id);
    $('#variety-select').empty();
    $.ajax({
        type: 'GET',
        url: '@Url.Action("fillVarietiesSelect", "Sales")',
        data: {species_id : species_id},
        success: function (result) {
            alert(result);
        }
    });
});

on change 事件正在触发,并弹出带有正确数据的警报。我在控制器方法处设置了断点,但执行似乎没有到达那里。

【问题讨论】:

  • 您是否在控制台或请求网络选项卡中看到任何错误?
  • ASP.NET MVC 抛出这么多控制台错误!但最后是:Empty string passed to getElementById(). jquery-1.10.2.js:188:0 GET XHR http://localhost:65244/@Url.Action(%22fillVarietiesSelect%22,%20%22Sales%22)
  • 网络面板显示 GET @Url.Action("fillVarietiesSelect", "Sales") 的 404 错误
  • 如果你让控制器操作方法返回字符串,那么它可以工作文件。当您返回 json 时,问题就来了。尝试返回 list 而不是 json
  • 尝试在Controller方法中将HttpGet改为HttpPost。此外,将 ajax 类型从 type: 'GET' 更改为 type:'POST'。

标签: javascript jquery ajax asp.net-mvc asp.net-ajax


【解决方案1】:

尝试完全按照以下方式进行

控制器:

    [HttpGet]
    public ActionResult receive2(string p)
    {
        ViewBag.name = p;
        List<string> lst = new List<string>() { p };
        return Json(lst,JsonRequestBehavior.AllowGet);

    }

客户端

      $.ajax({
            type: "GET",
            url: "Main/receive2", // the method we are calling
            contentType: "application/json; charset=utf-8",
            data: { "p": $("#txtname").val() },
             dataType:"json",
            success: function (result) {
                alert("yes");
                alert('Yay! It worked!tim' + result);
                window.location = "http://google.com";
                // Or if you are returning something

            },
            error: function (result) {
                alert('Oh no aa :(' + result[0]);
            }

        });

我已经检查过它的工作原理

【讨论】:

  • 做到了。我认为问题可能是试图将 val 称为 int 而不是字符串,并尝试将其作为 int 发送。
【解决方案2】:

我遇到了同样的问题,将参数从int 更改为string 解决了问题。

在我拥有的服务器端,

公共字符串 RemoveByDocumentID(int DocumentID)

改成

公共字符串 RemoveByDocumentID(字符串 DocumentID)

解决了这个问题。

在相同的上下文中,我有另一个同名的方法(重载方法)。这也是造成问题的原因,因此我将方法名称设为唯一。

【讨论】:

    【解决方案3】:

    您的 404 错误告诉您 @Url.Action 没有被视图引擎解析。 @ 是 Razor 语法,因此要使其正常工作,您需要为 C# 视图使用 .cshtml 扩展名或为 VB 视图使用 .vbhtml 扩展名,并使用 MVC 3 或更高版本。

    【讨论】:

    • 视图是index.cshtml
    猜你喜欢
    • 2014-07-27
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    相关资源
    最近更新 更多