【问题标题】:How to return complex JSON object from asp.net mvc Action Method如何从 asp.net mvc Action Method 返回复杂的 JSON 对象
【发布时间】:2014-08-01 14:15:53
【问题描述】:

我正在开发一个 asp.net mvc Web 应用程序,它连接到两个不同的数据库(我将它们命名为 dbA 和 dbB)。目前我需要创建一个 JSON 对象,其中包含来自不同表的值。

两个表如下:-

Table Technology from dbA,有以下字段:-

>> dbAID , Tag , db2ID

虽然来自 dbB 的 table Resource 有:-

>> Db2ID , Name

我有以下Action方法:-

public ActionResult AutoComplete(string term)

        {

var tech = dbA.Technology.Where(a=>a.Tag.StartWith(term));//select all technology that have their tags start with passed term

var db2IDList = tech.Select(a=>a.db2ID).ToArray();//create a list of db2ID



var resource = dbB.Resource.Where(db2IdList.Contains(a=>a.dbBID));//get the resource based on the db2IDList



JsonResult j = newJsonResult();

//here I want the json to contain the Technology.Tag + ResoruceNane, where the join is based on the db2Id stored insdie the technology table



        }

那么任何人都可以建议构造我的 JSON 对象的最佳方法是什么?

谢谢

【问题讨论】:

    标签: asp.net asp.net-mvc json entity-framework-5 asp.net-mvc-5


    【解决方案1】:

    匿名类型:http://msdn.microsoft.com/en-us/library/bb397696.aspx

    并且框架提供了 JsonResult,由 Json(object) helper 生成。

    例如return Json(new { field1 = resource.fieldOne, field2 = resource.fieldTwo })

    【讨论】:

    • 但是什么是 resource.fieldOne 和 resource.fieldTwo ??
    • 从你的问题:var resource = dbB.Resource.Where(db2IdList.Contains(a=>a.dbBID));//根据db2IDList获取资源
    • 但是这两个字段将如何链接在一起?
    【解决方案2】:

    你可以构建一个我认为更容易的列表:

    List<Object> _return=new List<object>();
    _return.Add(Technology.Tag);
    _return.Add(ResoruceName);
    Return Json(new {Success=true, _return});
    

    //然后在你的 Javascript 中强制转换获取这些对象,这将是一个易于使用的数组

    【讨论】:

    • 但是这种方法会加入这两个列表吗,我的意思是我如何知道哪个标签与哪个资源名称相关?
    猜你喜欢
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多