2013-05-10 14 views
10

mam problemu z JSON i listyC# Jak powrócić List <> jako JSON

Próbuję zwrócić listę klasie Chat Entity ale gdy próbuję wrócić IT skomlenie kompilatora. Próbowałem również zwrócić IEnumerable <> ale ten sam błąd przyszedł

co mogę zrobić?

tutaj jest moja funkcja, która zwraca element,

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

To Get Najnowszy funkcja Chat

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;  
} 

i to jest Ajax zadzwonić

$.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"); } 
}); 

Odpowiedz

18

Kompilator jest niezadowolony z twojego kodu, ponieważ mówisz, że twoja metoda (zgaduję metodę działania) jest d powrócił do List<Chat> i wracasz JsonResult. Jeśli używasz ASP.NET MVC, powinien wyglądać tak:

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

    return Json(list); 
} 
+0

To rozwiązało mój problem! Dzięki za jasne wyjaśnienie! –

Powiązane problemy