javascript - 为 mvc 绑定(bind)展平复杂的 json 对象

标签 javascript asp.net-mvc json

我的 Controller 正在像这样以 json 格式将对象图返回给 View

return Json(customer);

在 View 中我的 json 对象看起来像这样

{
    Name: 'Joe',
    Budget: { Amount: 500, Spend: 100 }
}

哪个正确映射到我的客户对象:

public class Customer 
{
    public string Name {get;set;}
    public Budget Budget{get;set;} 
}

public class Budget  
{
    public decimal Amount{get;set;}    
    public decimal Spend{get;set;} 
}

我想将同一个 json 对象传递回具有此签名的 Controller 上的另一个方法:

public ActionResult Method(Customer customer)

当我执行此操作时,会填充此客户的名称但不会填充 Budget 类,我理解这是为什么,因为 modelbinder 期望这样:{Name:'Joe','Budget.Amount':500,'Budget.Spend': 100

所以我必须选择: 1. 我可以以它想要的格式返回 json 对象,但我不知道怎么做,因为你不能这样做:

return Json(new { Budget.Amount= 500})
  1. 我可以在客户端扁平化 json 对象。是否有插件或方法可以做到这一点?

最佳答案

这是一个将对象转换为平面散列的函数

function flatten(json){
    var nj = {},
        walk = function(j){
            var jp;
            for(var prop in j){
                jp = j[prop];
                if(jp.toString() === "[object Object]"){
                    walk(jp);
                }else{
                    nj[prop] = jp;
                }
            }
        };
    walk(json);
    return nj;
}

关于javascript - 为 mvc 绑定(bind)展平复杂的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2210437/

相关文章:

javascript - ASP.NET 如何知道请求是否为 AJAX?

c# - 带有 Ninject 依赖注入(inject)的 ASP.NET MVC 应用程序中的 MongoDB 官方 C# 驱动程序

javascript - HTML 工作日历

javascript - 电子邮件正文始终为空

asp.net-mvc - ASP.NET 网络 API : authenticating using in memory hosting for Integration tests

java - 如何使用 Jackson 指定要序列化为 JSON 的特定字段?

javascript - 需要一些关于 PHP Session 多维数组到 Javascript 的建议

javascript - 在 JSON 脚本中格式化日期时间

javascript - Jquery 在鼠标悬停时每行显示不同的数据 ID

javascript - 我如何使用 jQuery 遍历此 DOM 并检索所需的文本?