通过ajax调用传递给mvc控制器时,在列表中获取空值

rup*_*r18 6 javascript ajax asp.net-mvc asp.net-mvc-4

我将我的列表传递给mvc控制器,但我在控制器中获取空值.但是当我在客户端显示警报时,我的列表中有值.

ajax电话

$("#addTiles").click(function() {
    userTiles = JSON.stringify({
        'userTiles': userTiles
    });
    alert("Entered function.");
    alert(userTiles[0].TileID);
    var url = '@Url.Action("AddTiles")';
    $.ajax({
        type: "GET",
        url: url,
        data: userTiles,
        success: function(d) {
            if (d.indexOf('"IsSessionExpired":true') != -1) {
                location.reload();
            } else {
                onAddTilesSuccessful(d);
            }
        },
        error: function() {
            errorInOperation();
        },
        contentType: "application/html; charset=utf-8",
        dataType: 'html'
    });
});

function onAddTilesSuccessful(e) {
    $("#tilesSubmissionMsg").append(e);
}

function errorInOperation(d) {
    $("#tilesSubmissionMsg").append("Something went wrong");
}
Run Code Online (Sandbox Code Playgroud)

mvc控制器

  public ActionResult AddTiles(List<UserTilesVM> userTiles)
    {
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

列表模型

public class UserTilesVM
{
    public int TileID { get; set; }
    public int TopPosition { get; set; }
    public int LeftPosition { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在javascript中列出

"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
Run Code Online (Sandbox Code Playgroud)

我也尝试过用stringfy发送我的列表,但这也行不通.

Dan*_*ing 5

您在AJAX设置中有两次contentType和dataType,具有不同的值,这将打破AJAX调用.

请记住,contentType是告诉服务器期望的数据类型,dataType用于确定从文档中返回的数据类型.

编辑:我看到你编辑了你的代码!

在这种情况下,由于您使用JSON.Stringify来修改要发送的数据,因此您将使用contentType: "application/json; charset=utf-8",内容类型,因为您要将JSON数据发送到后端.


小智 5

使用:[HttpGet]AddTilestype: "GET"在Ajax命中时使用的方法.

[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
     return View();
}
Run Code Online (Sandbox Code Playgroud)

如果仍然不起作用,那么尝试type: "POST"Ajax命中和方法使用[HttpPost]

[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)