C# MVC 通过 AJAX 发送列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18807302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:15:43  来源:igfitidea点击:

MVC Send list through AJAX

c#jqueryajaxasp.net-mvc

提问by Halaster

Okay, I've seen tons of questions posted regarding this question, but none of the answers has actually worked for me, here's my AJAX:

好的,我已经看到很多关于这个问题的问题,但没有一个答案对我有用,这是我的 AJAX:

$.ajax({
        url: "/FilterSessions/GetFilterSession",
        type: "GET",
        dataType: "json",
        data: jsonFilters,
        traditional: true,
        success: function (response) {
            //Haha, it's never entering here. not really.
        }
    });

var "jsonFilters" contains an array with the following data:

var "jsonFilters" 包含一个包含以下数据的数组:

[0] = { Path: "Test", Name: "More testing", Value: "Test Value" },
[1] = { Path: "Test", Name: "More testing", Value: "Test Value" } 

And this is my controller:

这是我的控制器:

public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
    //Do things

    return Json(false, JsonRequestBehavior.AllowGet);
}

jsonFilters always remains null... I have also tried adding contentType: "application/json; charset=utf-8"to the AJAX call... but that didn't really do anything

jsonFilters 始终保持为空...我也尝试添加contentType: "application/json; charset=utf-8"到 AJAX 调用中...但这并没有真正做任何事情

Finally, the class FilterSessionModelis structured as follows:

最后,该类FilterSessionModel的结构如下:

 public class FilterSessionModel
    {
        public string Path { get; set; }
        public string Name { get; set; }
        public string Value { get; set; }
    }

Any ideas as to what I might be missing or what might be happening?

关于我可能会遗漏什么或可能发生什么的任何想法?

Things I've tried so far:

到目前为止我尝试过的事情:

Setting "traditional: true", setting "contentType", using JSON.stringify and attempting to accept a string in the MVC Controller (no-go)

设置“traditional: true”,设置“contentType”,使用 JSON.stringify 并尝试在 MVC 控制器中接受字符串(禁止)

UPDATE: Thanks to the answer below I realized that what was missing was to send over the data with the param Id like so:

更新:感谢下面的答案,我意识到缺少的是使用参数 Id 发送数据,如下所示:

 data: "{param1ID:"+ param1Val+"}"

采纳答案by aximili

I think what you are looking for is answered here:

我认为您正在寻找的答案在这里:

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

使用 jQuery Ajax 将对象列表传递到 MVC 控制器方法中

回答by Bill Blankenship

I would try switching out the type on your action.

我会尝试在你的动作中切换类型。

List<FilterSessionModel>

Pretty sure the above is not going to work, I would try something like Object.

很确定上面的方法行不通,我会尝试像 Object.

Or possibly a string that I would then use newton json dll to push into your List of Class.

或者可能是一个字符串,然后我将使用 newton json dll 推送到您的类列表中。

The problem boils down to your action being unable to figure out the type, assuming you are checking your data prior to the ajax get being called.

问题归结为您的操作无法确定类型,假设您在调用 ajax 之前检查您的数据。

**Update due to more info. Add in the error portion and view those vars on return from your controller, also fire up fiddler and watch what your are getting for http numbers.

**由于更多信息而更新。添加错误部分并查看从您的控制器返回的那些变量,同时启动 fiddler 并观察您获得的 http 数字。

$.ajax({
    type: "POST",
    url: "Servicename.asmx/DoSomeCalculation", 
  data: "{param1ID:"+ param1Val+"}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        UseReturnedData(msg.d);
    },
    error: function(x, t, m, b) {
        //Look at the vars above to see what is in them.
    }
});

回答by cmcquillan

First off I'm making the assumption that your $.ajaxis for JQueryand not some other Javascript framework. Please correct me if that's wrong.

首先,我假设您$.ajax是用于JQuery而不是其他一些 Javascript 框架。如果那是错误的,请纠正我。

ASP.NET MVC can actually do what you are asking it to (resolve data sent via AJAX to a List<FilterSessionModel>, but it seems to have a difficult time doing it via a GET request. It would help to know which version of ASP.NET MVC you are using, as more is required to get this working on the older versions. However, what I'm suggesting should work on MVC 3 or 4.

ASP.NET MVC 实际上可以按照您的要求执行(解析通过 AJAX 发送到 a 的数据List<FilterSessionModel>,但通过 GET 请求执行此操作似乎很困难。这将有助于了解您使用的是哪个版本的 ASP.NET MVC正在使用,因为需要更多才能在旧版本上运行。但是,我建议的内容应该适用于 MVC 3 或 4。

When you send AJAX via JQuery using a GET request and passing it a JavaScript array, this is what you are sending to the server:

当您使用 GET 请求通过 JQuery 发送 AJAX 并将其传递给 JavaScript 数组时,这就是您发送到服务器的内容:

http://localhost:50195/FilterSessions/GetFilterSession?undefined=&undefined=

It's no wonder the model is null because no data is actually being sent.

难怪模型为空,因为实际上没有数据被发送。

I believe ASP.NET can accept objects (and even arrays of objects) like this, but it won't do so with it formatted as JSON (like via JSON.stringify) as that just results in the following request:

我相信 ASP.NET 可以接受这样的对象(甚至对象数组),但它不会这样做,因为它格式化为 JSON(如通过 JSON.stringify),因为这只会导致以下请求:

http://localhost:50195/FilterSessions/GetFilterSession?[{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22},{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22}]

The way you probably want to do this is with a POST request. ASP.NET MVC will actually accept a JSON string as POST data and will decode it and resolve the model properly. Your AJAX code works fine with a couple modifications:

您可能想要执行此操作的方式是使用 POST 请求。ASP.NET MVC 实际上会接受一个 JSON 字符串作为 POST 数据,并将对其进行解码并正确解析模型。您的 AJAX 代码可以通过一些修改正常工作:

$.ajax({
    url: "/FilterSessions/GetFilterSession",
    type: "POST", //Changed to POST
    dataType: "json",
    data: JSON.stringify(jsonFilters), //Pack data in a JSON package.
    contentType: "application/json; charset=utf-8", //Added so ASP recognized JSON
    traditional: true,
    success: function (response) {
        alert('Success!');
    }
});

The controller you posted should recognize POST data already, but in case it doesn't, a simple [HttpPost]attribute is all you need:

您发布的控制器应该已经识别 POST 数据,但如果不能,[HttpPost]您只需要一个简单的属性:

[HttpPost]
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
    //Do things

    return Json(false, JsonRequestBehavior.AllowGet);
}

回答by Sanket

javascript or ajax call never type cast the object. . .you need to set type of the controller side parameter either string or List else you can also set the Object type. . If you modified codein that way.. .Your code definitely work !!!

javascript 或 ajax 调用从不类型转换对象。. .您需要设置控制器端参数的类型,字符串或列表,否则您也可以设置对象类型。. 如果你以这种方式修改了代码......你的代码肯定有效!!!

回答by Athul Nalupurakkal

$.ajax({
    url: "/FilterSessions/GetFilterSession",
    type: "GET",
    dataType: "json",
    data:JSON.stringify({ 'jsonFilters': jsonFilters}),
    contentType: 'application/json; charset=utf-8',
    success: function (response) {
        //Do your action
    }
});