ASP.net MVC Controller receiving null array when sending from Ajax

flashsplat :

I've been at this for what seems like days now. This should be so simple. Why isn't this working? My URL looks like this:

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

I want to send c15905d7-8216-4e81-ac15-2fafd10b49e8 & 80515cad-070a-4d61-a7e3-f2dbb1968c9d to my controller.

Here is the last thing I've tried (of 20748 attempts):

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);
        }
    });
}

Controller:

[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])
    });
}

My array is always null. Is there a better/easier/more efficient way to do this? One that works? Thanks!

Jerdine Sabio :

Option 1

In your ajax call, no need to wrap the list string with {}. Simply use;

data:pathArray

Option 2

Make a class that would serve as the model where the properties would be bound.

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

Then in your controller

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=397511&siteId=1