2013-05-10 49 views
10

我有使用JSON問題,列出C#如何返回列表<>爲JSON

我試圖返回聊天實體類的列表,但是當我試圖返回它的編譯器哼唧。 我也嘗試過返回IEnumerable <>但出現同樣的錯誤

我該怎麼辦?

這裏是我的功能正在恢復的項目,

public List<Chat> GetNewChatPosts() 
{ 
    var userID = U_rep.GetUserID(User.Identity.Name); 
    var list = G_rep.GetNewestChat(0, userID); 
    return Json(list); 
} 

這是獲取最新的聊天功能

public List<Chat> GetNewestChat(int gameID, int userID) 
{ 
    var pos1 = (from p in n_db.ChatPos 
       where p.userID == userID && gameID == p.gameID 
       select p).SingleOrDefault(); 
    int pos; 
    if (pos1 == null) 
    { 
     pos = 0; 
     ChatPo n = new ChatPo(); 
     n.gameID = gameID; 
     n.userID = userID; 
     n.chatID = pos; 

     n_db.ChatPos.InsertOnSubmit(n); 
     n_db.SubmitChanges(); 
    } 
    else 
    { 
     pos = pos1.ID; 
    } 

    var newIEnumerable = from chat in n_db.Chats 
          where chat.ID > pos 
          orderby chat.ID descending 
          select chat; 
    List<Chat> newestChat = new List<Chat>(); 
    foreach (var n in newIEnumerable) 
    { 
     newestChat.Add(n); 
    } 

    var last = newIEnumerable.Last(); 

    pos1.ID = last.ID; 

    n_db.SubmitChanges(); 

    return newestChat;  
} 

,這是Ajax調用

$.ajax({ 
    type: "GET", 
    url: "/Game/GetNewChatPosts", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    data: JSON.stringify(text), 
    success: function (data) { 
     alert("success post"); 
    }, 
    error: function() { alert("error post"); } 
}); 

回答

18

編譯器對你的代碼不滿意,因爲你在說你的方法(我猜的是action方法)是d定義爲返回List<Chat>,您將返回JsonResult。如果你使用ASP.NET MVC,它應該看起來像這樣:

public ActionResult GetNewChatPosts() 
{ 
    var userID = U_rep.GetUserID(User.Identity.Name); 
    var list = G_rep.GetNewestChat(0, userID); 

    return Json(list); 
} 
+0

這解決了我的問題!感謝您的明確解釋! – 2016-07-12 23:49:13

相關問題