【问题标题】:ASP.net MVC Controller receiving null array when sending from AjaxASP.net MVC 控制器从 Ajax 发送时接收空数组
【发布时间】:2020-04-03 15:49:06
【问题描述】:

我似乎已经有好几天了。这应该很简单。为什么这不起作用? 我的网址如下所示:

https://example.com/photos/gallery/c15905d7-8216-4e81-ac15-2fafd10b49e8/80515cad-070a-4d61-a7e3-f2dbb1968c9d

我想将c15905d7-8216-4e81-ac15-2fafd10b49e880515cad-070a-4d61-a7e3-f2dbb1968c9d 发送给我的控制器。

这是我尝试过的最后一件事(共 20748 次尝试):

function setViewed() {
    var pathArray = window.location.pathname.split('/');

    $.ajax({
        type: "PUT",
        url: '/api/Customers/',
        data: { 'pathArray': pathArray },
        dataType: "json",
        traditional: true,
        success: function (response) {
            alert(response.msg);
        }
    });
}

控制器:

[HttpPut]
public IHttpActionResult SeenIt(List<String> pathArray)
{

    // Don't update if it's the client looking at a customer's gallery:
    if (pathArray[3] == User.Identity.GetUserId()){
        return Json(new
        {
            msg = String.Format("ClientID: {0} | CustomerID: {1}", pathArray[3], pathArray[4])
        });
    }

    var customer = db.Customers.FirstOrDefault(c => c.CustomerID == Guid.Parse(pathArray[4]));
    customer.Accessed = true;

    db.SaveChanges();
    return Json(new
    {
        msg = String.Format("ClientID: {0} | CustomerID: {1}", pathArray[3], pathArray[4])
    });
}

我的数组始终为空。有没有更好/更容易/更有效的方法来做到这一点?一个有效的?谢谢!

【问题讨论】:

    标签: jquery ajax asp.net-mvc


    【解决方案1】:

    选项 1

    在您的 ajax 调用中,无需使用 {} 包装列表字符串。只需使用;

    data:pathArray
    

    选项 2

    创建一个类,作为绑定属性的模型。

    public class ReceiveModel{
       public List<string> pathArray {get;set;}
    }
    

    然后在你的控制器中

    public IHttpActionResult SeenIt(ReceiveModel model)
    {
       ...
    }
    

    【讨论】:

    • 谢谢。我只是尝试了两者并得到了相同的结果。模型和/或数组到达 null :(.
    • 哦,等等,我将 jquery 切换回 `{ 'pathArray': pathArray }`,我认为它正在工作!由天哪..
    • @flashsplat 哈哈!选项 2 在哪里有效?
    • 是的!我现在还有其他问题,但我会解决的。至少我现在得到了控制器中的数据。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2020-05-11
    相关资源
    最近更新 更多