开发者

Passing object(s) to a Controller Action

开发者 https://www.devze.com 2022-12-30 02:17 出处:网络
I\'m attempting to use jQuery to do a $.post() to an MVC controller action. Here\'s the jQuery calls:

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 fo开发者_运维技巧rmat, 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.


Try changing your action signature to:

Function MyAction(ByVal username As string, password as string, ByVal dateRange As String) As ActionResult
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号