skip to Main Content

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!

2

Answers


  1. 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)
    {
       ...
    }
    
    Login or Signup to reply.
  2. I know this is an old post but for anyone using ajax to post versus straight JS I found that adding this helped:
    contentType: "application/json; charset=utf-8",

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search