【问题标题】:Posting complex types using Jquery to Asp.Net MVC使用 Jquery 将复杂类型发布到 Asp.Net MVC
【发布时间】:2009-07-14 03:11:00
【问题描述】:

我正在尝试创建一个从 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; }
}

我发布的 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 格式有问题,但根本无法弄清楚。任何见解将不胜感激。

最好的问候,感谢您的宝贵时间。

哈尔

【问题讨论】:

    标签: jquery asp.net-mvc json


    【解决方案1】:

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

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

    如果你的对象是这样的:

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

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

    【讨论】:

    • 所以它更喜欢扁平结构?谢谢你的提示。我会在上午检查它并发布我的结果。
    • 哇,这真的很不幸。我想知道他们是否打算在 2.0 版本中更改它... var obj1 { id : 1, obj2 : { prop : val } };比 var obj 1 { id : 1, "obj2.prop" : val };在我看来。如果您将类型动态地公开给 JavaScript,那么使用起来会更容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多