Passing object(s) to a Controller Action

Posted by Nicholas H on Stack Overflow See other posts from Stack Overflow or by Nicholas H
Published on 2010-05-08T00:17:36Z Indexed on 2010/05/08 0:28 UTC
Read the original article Hit count: 443

Filed under:

I'm attempting to use jQuery to do a $.post() to an MVC controller action. Here's the jQuery calls:

var _authTicket = { username: 'testingu', password: 'testingp' };

function DoPost() {    
    var inputObj = { authTicket: _authTicket, dateRange: 'ThisWeek' };            
    $.post('/MyController/MyAction', inputObj, PostResult);
}

function PostResult(data) {
    alert(JSON.stringify(data));
}

Here's the controller action:

    <HttpPost()> _
    Function MyAction(ByVal authTicket As AuthTicket, ByVal dateRange As String) As ActionResult
        Dim u = ValidateUser(authTicket)
        If u Is Nothing Then Throw New Exception("User not valid")

        ' etc..

    End Function

The problem is, MyAction's "authTicket" parameter is all empty. The second "dateRange" parameter gets populated just fine. I'm pretty sure that the issue stems from jQuery turning the data into key/value pairs to POST to the action. MVC must not understand the format, at least when it's an object with it's own properties.

The name/value pair format that jQuery is converting to is like:

authTicket[username] = "testingu"
authTicket[password] = "testingp"

Which in turn gets made into x-www-form-urlencoded'd data:

authTicket%5Busername%5D=testingu
&authTicket%5Bpassword%5D=testingp

I guess I could always have "username" and "password" properties in my actions, but that seems wrong to me. Any help would be appreciated.

© Stack Overflow or respective owner

Related posts about asp.net-mvc