使用Jquery向Asp.Net MVC发布复杂类型

时间:2009-07-14 03:11:00

标签: jquery asp.net-mvc json

我正在尝试从Jquery $ .ajax帖子中创建一个接收复杂类型的休息服务,但我似乎无法说服mvc在控制器中保存我的复杂对象。

以下是我的一些代码:

控制器:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChargeUser(TransactionInfo transactionInfo, CardInfo cardInfo) {
/// both transactionInfo and cardInfo are un-populated.   
}

的DTO:

[Serializable] public class CardInfo : ICardInfo {
        public string CCNumber { get; set; }
        public int ExpirationMonth { get; set; }
        public int ExpirationYear { get; set; }
        public string CardVerificationValue { get; set; }
}

[Serializable]
public class TransactionInfo : ITransactionInfo
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string Country { get; set; }
        public string PostalCode { get; set; }
        public string Currency { get; set; }
        public decimal Amount { get; set; }
}

我正在POST的示例JSON,如下所示:

"{"transactionInfo":{"FirstName":"Hal","LastName":"Lesesne","Address1":"504 Anytown Drive","Address2":"Sample Address 2","City":"Boone","Region":"NC","Country":"US","PostalCode":"28607","Currency":"USD","Amount":"1.5"},"cardInfo":{"CCNumber":"4222 2222 2222 2222","ExpirationMonth":"1","ExpirationYear":"2009","CardVerificationValue":"333"}}"

使用像这样的jquery调用:

function jQueryPost(data, action, onSuccess, onFailure) {
    $.ajax({ 
        url: action,
        type: 'POST',
        data: data,
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        error: onFailure,
        success: onSuccess
    });    
}

我在调试时遇到了断点,但是没有填充transactionInfo和cardInfo,只有stings(null)和numerics(0)的默认值。

我认为我的json格式出错了,但根本无法理解。任何见解将不胜感激。

致以最诚挚的问候,谢谢您的时间。

哈尔

1 个答案:

答案 0 :(得分:3)

我认为模型绑定器期望查询字符串看起来的方式更像是:

TransactionInfo.FirstName=Hal&TransactionInfo.LastName=Lesesne&...

如果您的对象如下:

{ "TransactionInfo.FirstName" : "Hal", "TransactionInfo.LastName", "Lesesne", ... }

然后我认为它会将它正确地序列化为MVC期望的查询字符串。