jQuery Ajax json 到 MVC5 控制器:传递包含集合的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22540739/
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-27 01:58:10  来源:igfitidea点击:

Ajax json to MVC5 controller: Passing object containing a collection

jqueryasp.net-mvcjsonasp.net-mvc-5

提问by Arjay H.

Folks, I've attempted this on MVC4 and MVC5.

伙计们,我已经在 MVC4 和 MVC5 上尝试过这个。

I need to pass an object with a few properties and a collection from the client to the controller.

我需要将一个带有一些属性的对象和一个集合从客户端传递给控制器​​。

I've defined the model in C# as:

我在 C# 中将模型定义为:

public enum RequestMode { ReadOnly = 0, Edit = 1}

public class DataRequest
{
    public int ProjectId { get; set; }
    public RequestMode Mode { get; set; }
    public List<PageRequest> PageRequests { get; set; }

    public DataRequest()
    {
        PageRequests = new List<PageRequest>();
    }
}

public class PageRequest
{
    public int Id { get; set; }
    public int PageCurrent { get; set; }
    public int RowCountPerPage { get; set; }
}

The MVC Controller is defined as (just using it to set a breakpoint to check the request values):

MVC 控制器定义为(仅使用它来设置断点以检查请求值):

[HttpPost]
public JsonResult Test(DataRequest request)
{
    return new JsonResult();
}

The Index.cshtml client contains the ajax call:

Index.cshtml 客户端包含 ajax 调用:

<script type="text/javascript">
    var RequestMode = { ReadOnly: 0, Edit: 1 };

    var dataRequest = { ProjectId: 17, Mode: RequestMode.Edit, PageRequests: new Array() };
    var pageRequest = { TableId: 3165, PageCurrent: 4, RowCountPerPage: 30 };
    dataRequest.PageRequests.push(pageRequest);

    $(document).ready(function () {
        $.ajax({
            data: dataRequest,
            type: 'POST',
            cache: false,
            url: '/Home/Test',
            success: function (data) {
            },
            fail: function (data) {

            }
        });

    });

</script>

I start debugging, the page loads and my breakpoint in the controller Test method gets hit.

我开始调试,页面加载,我在控制器 Test 方法中的断点被击中。

In the debugger, the request object shows up as: Mode: Edit PageRequests: Count = 1 ProjectId: 17

在调试器中,请求对象显示为: Mode: Edit PageRequests: Count = 1 ProjectId: 17

When I expand the PageRequests collection property, I see: {Mvc5WebTest.Controllers.PageRequest} Id: 0 PageCurrent: 0 RowsPerPage: 0

当我展开 PageRequests 集合属性时,我看到: {Mvc5WebTest.Controllers.PageRequest} Id: 0 PageCurrent: 0 RowsPerPage: 0

I would expect the PageRequest object to be populated with the values I've set (i.e. 3165, 4, 30)

我希望 PageRequest 对象填充我设置的值(即 3165、4、30)

Using Fiddler, I see that the complete DataRequest object is getting turned into Json correctly, but it seems that the MVC controller can't turn it back into the C# object.

使用 Fiddler,我看到完整的 DataRequest 对象正确地转换为 Json,但似乎 MVC 控制器无法将其转换回 C# 对象。

As a workaround, I can modify the ajax call on the client to var cdr = JSON.stringify(dataRequest);

作为一种解决方法,我可以将客户端上的 ajax 调用修改为 var cdr = JSON.stringify(dataRequest);

$.ajax({
    dataType: 'json',
    type: 'GET',
    data: { jsonRequest: cdr },
    ...

And then in the controller

然后在控制器中

[HttpGet]
public ActionResult Test(string jsonRequest)
{
    var request = JsonConvert.DeserializeObject<DataRequest>(jsonRequest);
    return new JsonResult();
}

This works, but I'd rather not pass the data as a string.

这有效,但我宁愿不将数据作为字符串传递。

Can anyone shed some light as to what is going on and what I need to do to get the collection populated?

任何人都可以阐明正在发生的事情以及我需要做些什么来填充集合?

回答by vbn

Because you're posting JSON data, you have to convert the object to string by using JSON.stringifyand declare the contentType: "application/json; charset=utf-8"

因为您要发布 JSON 数据,所以必须通过使用JSON.stringify和声明将对象转换为字符串contentType: "application/json; charset=utf-8"

$(document).ready(function () {
    $.ajax({
        data: JSON.stringify(dataRequest),
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: '/Home/Test',
        success: function (data) {
        },
        fail: function (data) {

        }
});

I also noticed that in C# code, you defined PageRequestas

我还注意到在 C# 代码中,你定义PageRequest

public class PageRequest
{
    public int Id { get; set; }
    public int PageCurrent { get; set; }
    public int RowCountPerPage { get; set; }
}

While in js,

在js中,

var pageRequest = { TableId: 3165, PageCurrent: 4, RowCountPerPage: 30 };

There is a conflict between Idin C# and TableIdin js. You will have to use one or the other.

IdC# 和TableIdjs之间存在冲突。您将不得不使用其中之一。

回答by Marko

You have to specify that you're sending JSON over because the default content type is string:

您必须指定要发送 JSON,因为默认内容类型是字符串:

$(document).ready(function () {
    $.ajax({
        data: dataRequest,
        type: 'POST',
        cache: false,
        contentType: "application/json; charset=utf-8",
        url: '/Home/Test',
        success: function (data) {
        },
        fail: function (data) {

        }
    });