簡體   English   中英

如何從外鍵關聯表中獲取數據列表是mvc中的json格式

[英]How to get list of data from foreign key associated table is json format in mvc

我用外鍵關聯創建了兩個表(問題,答案),我需要基於questionID列的答案列表,因為我需要linq查詢。 我是mvc的初學者,任何人都可以幫助我

控制器代碼:

public JsonResult displayQuestion()
{
     var result = from q in Db.questions
                  join a in Db.answers on q.Qid equals a.questionID
                  select new { q.QText, q.Qid, a.answer1 };
     return Json(result, JsonRequestBehavior.AllowGet);
}

json結果:

[
    {"QText":"result of 2+2","Qid":2,"answer1":"2"},
    {"QText":"result of 2+2","Qid":2,"answer1":"4"},
    {"QText":"result of 2+2","Qid":2,"answer1":"6"},
    {"QText":"result of 2+2","Qid":2,"answer1":"8"}
]

但我需要如下:

{
   "QText": "result of 2+2",
   "Qid": 2,
   "answer1": [
      { "option1": "2" },
      { "option1": "4" },
      { "option1": "6" },
      { "option‌​1": "8" }
   ]
}

不要進行連接,而是獲取所需的問題信息,然后執行子查詢以獲取特定問題的答案:

public JsonResult displayQuestion()
{
     var result = from q in Db.questions
                  select new { 
                    q.QText, 
                    q.Qid, 
                    answer1 = (from a in Db.answers 
                               where a.questionID == q.Qid
                               select new { option1 = a }).ToList()
                  };

     return Json(result, JsonRequestBehavior.AllowGet);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM