简体   繁体   English

用于ajax调用的ASP.NET控制器方法

[英]ASP.NET controller method for ajax call

I have a page with a multiselect list of strings. 我有一个包含多选字符串列表的页面。 When I select multiple items and hit apply I want to make an ajax call and pass in the values. 当我选择多个项目并点击应用时,我想进行ajax调用并传递值。 When I debug the method in the controller the parameter is empty. 当我在控制器中调试方法时,参数为空。

HomeController 家庭控制器

[HttpGet]
public string GetTopLogEvents(string[] filters)
{
    // ........
    return "";
}

scripts.js scripts.js

$('.js-event-level-filter-apply').on('click', function() {
    var $this = $(this);
    var $filterList = $('.js-event-level-filter');
    var filters = $filterList.val();

    var obj = {
        filters: []
    };

    $.each(filters, function(key, value) {
        obj.filters.push(value);
    });

    $.ajax({
        type: "GET",
        url: '/Home/GetTopLogEvents',
        data: obj.filters,
        success: function(data) {
            console.log(data);
        }
    });
});

If I put a breakpoint in the controller it hits, but filters is empty. 如果我在控制器中放置一个断点,它将命中,但过滤器为空。 What am I doing wrong? 我究竟做错了什么?

It could be that you need to "stringify" your array. 可能是您需要“字符串化”您的数组。

I would firstly change the ajax data section to look like this: 我首先将ajax数据部分更改为如下所示:

data: {filters: obj.filters}

If that doesn't work, I'd try 如果那行不通,我会尝试

data: {filters: stringify(obj.filters)} 

The exact syntax of the latter might be incorrect so please check that. 后者的确切语法可能不正确,因此请检查一下。

Can you open up your browser, hit F12, and put a breakpoint directly on the $.ajax line (in the file in sources tab). 您能打开浏览器,按F12键,然后在$ .ajax行上直接放置一个断点吗(在“源”选项卡中的文件中)。 Then, run that method. 然后,运行该方法。 When the thread stops on the breakpoint, can you then open up the console tab, and type "obj.filters" and press enter. 当线程在断点处停止时,是否可以打开控制台选项卡,并键入“ obj.filters”并按Enter。

Does it say "undefined"? 它说“未定义”吗?

Looking at your code, it "shouldn't" be undefined, but that would certainly be a good start. 查看您的代码,它“应该”是不确定的,但是那肯定是一个好的开始。

Also, stringifying (JSON.stringify())the information you send in, and then doing JObject calls (c#) to turn it back into an object array might work. 同样,对发送的信息进行字符串化(JSON.stringify()),然后执行JObject调用(c#)将其转换回对象数组也可能有效。

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

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