Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
My Model:

C#
 public class Cls{
    public int Id {get;set;}
    public string name {get;set;}
}


My Controller:

C#
public JsonResult jsonClassList()
       {
           var classes = from c in db.Cls
                         select c;
           return Json(new { Classes = classes }, JsonRequestBehavior.AllowGet);
       }


What I have tried:

I want to get list of data in json format?
C#
{
  Classes:
  [
  {
    Id : 1,
    name: one
  },
  {
    Id : 2,
    name: two
  },
  {
    Id : 3,
    name: three
  }
 ]
}
Posted
Updated 11-Jul-16 2:58am
v4
Comments
Suvendu Shekhar Giri 11-Jul-16 2:05am    
What is the JSON result you are getting?
Muhammad Shan 11-Jul-16 2:08am    
I'm getting this error:

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Clas_9509CA648588A0D8B4283C10ABF34A411C9EAFC459E3E2D68EDA7B7326F2B1B1'.
Karthik_Mahalingam 11-Jul-16 2:19am    
that is not a valid json.
Muhammad Shan 11-Jul-16 2:22am    
{ Classes:
[
{
Id : 1,
name: one
},
{
Id : 2,
name: two
},
{
Id : 3,
name: three
}
]
}
Karthik_Mahalingam 11-Jul-16 2:37am    
you want this output?

try this

C#
public JsonResult jsonClassList()
       {
           var classes =   db.Cls.ToList();
           var obj = new { Classes = classes };
           return Json(obj, JsonRequestBehavior.AllowGet);
       }
 
Share this answer
 
I can't see how the code you posted would give you that error so I think you're cutting down the code and missing out something important. If your Cls table has more columns that id and name, try

C#
public JsonResult jsonClassList()
       {
           var classes = from c in db.Cls
                         select new {id = c.Id, name = c.name};
           return Json(new { Classes = classes }, JsonRequestBehavior.AllowGet);
       }
 
Share this answer
 
JsonResult Type in MVC[^]

public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900