views:

195

answers:

2

I'm using Asp.Net-Mvc, I have this method in my controller:

    [AcceptVerbs(HttpVerbs.Post)]    
    public ActionResult LinkAccount(string site, object id)
    {
        return this.Json(id);
    }

Here's the ajax method that calls it:

$.post("/Account/LinkAccount", { site: "Facebook", 
                               id: FB.Facebook.apiClient.get_session().uid },
        function(result) {
            alert(result); 
        }, "json"
    );

returning this.Json(id); makes the alert work... it alerts 7128383 (something similar to that).

but if I change this.Json(id) to this.Json(Conver.ToInt64(id)); the alert does not fire...

Any idea of why I can't convert an object received from an object to a long?

I already know changing the LinkAccount method to accept a long instead works just fine. It's just I need it as an object because some other sites I'm linking up have strings for id's rather than longs.

UPDATE: I tried running the code on localhost so I could set a breakpoint. First I changed the line return this.Json(Convert.ToInt64(id)); to long idAsLong = Convert.ToInt64(id));. Here's what the debugger is telling me:

  • When I hover over id it says: "id | {string[1]}"
    and when I press the plus button is shows: "[0] | '7128383'"

  • When I hover over idAsLong, it says: "idAsLong | 0"

Why isn't it converting it properly?

+1  A: 

I don't think the model knows how to make an object out of the request parameter, so what you get is a null. Try accepting id as a string and converting it to a long.

[AcceptVerbs(HttpVerbs.Post)]    
public ActionResult LinkAccount(string site, string id)
{
    return this.Json( Convert.ToInt64(id) );
}

Or you could leave it as a string, since you're just passing it back via JSON (which will just serialize it back as a string anyway). You'd only need to do the conversion if you needed it as a long on the server.

tvanfosson
+1  A: 

Shahklapesh said:

so, id is an array of string, which you can't convert to Int64. The 0th element contains the actual ID (which can be converted to Int64). long idAsLong = Convert.ToInt64(id[0]);

Which was correct, except that since id is an object, you cannot use indexes like [0]. Instead, what worked, was this: Convert.ToInt64(((string[])id)[0])

Thanks for the help Shahklapesh!

Matt