4

I try to return Entity Framework Objects as Json with the following method in my Controller:

  public JsonResult EventList() {
        var results = from s in db.Events
                      select new
                      {
                          OrderID = s.EventID,
                          OrderTitle =s.EventType,
                          OrderDate = s.Title
                      };

return Json(results);
}

I get a server error 500 when entering the page /events/EventList/. Also a Jquery get request returns no data. What is the correct way to return the results in Json format?

Update:

This seems to work. But I need results from the database.

   public ActionResult EventList() {

        Event test = new Event
        {
            EventID = 1,
            Title = "test",
            Description = "test"
        };

        return Json(new { event = test }, JsonRequestBehavior.AllowGet);
    }
8
  • 1
    Are you making a GET call? If so, you need return Json(results, JsonRequestBehavior.AllowGet); Commented Oct 20, 2015 at 12:04
  • Try to add .ToArray() to results: return Json(results.ToArray()) Commented Oct 20, 2015 at 12:07
  • @StephenMuecke if I add JsonRequestBehavior.AllowGet); I get the HTML of the index view as result Commented Oct 20, 2015 at 12:10
  • @KirillBestemyanov Thanks, but no result Commented Oct 20, 2015 at 12:11
  • @JasonB, What you you mean the HTML? - your returning json, not a view. Commented Oct 20, 2015 at 12:13

2 Answers 2

13

Edit: 2019

This answer still gets upvotes - if you're going down this road I really really suggest you just save yourself the future headaches and use a DTO. Serializing your entity is probably faster for now but (and I have learned this the hard way) - you are going to hate yourself in a years time.

New answer - updated for 2018:

The original answer below will work every time and if you're using lazy loading, it may still be the best solution. Without lazy loading though, you can do the following with Newtonsoft.JSON:

var settings = new JsonSerializerSettings()
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        Error = (sender, args) =>
        {
            args.ErrorContext.Handled = true;
        },
    };

using(var context = new myContext())
{
    var myEntity = myContext.Foos.First();
    return JsonConvert.SerializeObject(myEntity, settings);
}

Which basically will serialize anything that's been included in the entity framework request, while ignoring any errors and reference loops.

The drawback to this method is that controlling what gets serialized is harder and if you're performance conscious, you may need to start decorating your generated Entity Framework classes with a pattern like

// a new partial class extending the Foo generated class, allowing us to apply an interface
[MetadataType(typeof(IFooMetaData))]
public partial class Foo : IFooMetaData
{
}

// meta data interface, forcing json ignore on Foo.Bars
public interface IFooMetaData
{
    [JsonIgnore]
    ICollection<Bar> Bars {get;set;}
}

Original answer - 2015:

Can get this response:

[
{
"OrderID": 1
},
{
"OrderID": 2
},
{
"OrderID": 3
}
]

from this:

    public JsonResult Test()
    {
        var events = new List<Event>()
        {
            new Event() {EventId = 1},
            new Event() {EventId = 2},
            new Event() {EventId = 3}
        };


        var results = events.Select(e => new
        {
            OrderID = e.EventId
        }).ToList();

        return new JsonResult() { Data = results, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

So yours should be something like

    public JsonResult Test()
    {
        var results = db.Events.Select(e => new
        {
            OrderID = e.EventId
        }).ToList();

        return new JsonResult() { Data = results, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

edit

re-posted with tested code

Sign up to request clarification or add additional context in comments.

2 Comments

It redirects to the default error page (views/shared/error.chtml)
Edited the answer to something I've just tried and tested
0

In the controller: for example

List<categories> data = context.categories.toList();  //to here all right

now, the problem with the serialization for "data" for send the json result... i just used a struct to replace the List how???

just watch:

in the same controller ...

   struct categories_struct{
   public fieldname {get;set;}
   //the same for others firelds (same the model)
  }

now, in the ActionResult or maybe in jsonresult :

  List<categorias> data = contexto.categorias.ToList();  //I use the EF
 List<catego> data2 = new List<catego>();              //create the struct var

        foreach (categorias item in data)    //fill the struct with data
        {
            catego item2 = new catego();
            item2.codcat = item.codcat;
            item2.nomcat = item.nombrecat;
            item2.descripcion = item.descripcion;
            data2.Add(item2);
        }

        //here, Data contains all data2
        return Json(new { Data = data2 }, JsonRequestBehavior.AllowGet); 

in the view:

$.ajax({
            url: "/Categorias/getTabla",
              dataType: "JSON",
            type: "POST",
        }).done(function (respuesta) {
            var data = JSON.parse(JSON.stringify(respuesta));
            console.log(respuesta);
            alert('exito');
        }).fail(function () {
            alert('oh no, again!');
        });

///

is my solution for this problem

1 Comment

Typing laughing into the answer degrades the impression of helpfulness. Also, please do the job hunting the way StackOverflow supports, not by sneaking it into answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.