Otrzymywanie danych z json.

0

Witam,
Dla testu próbuję wyświetlić wszystkie quizy bez przeładowywania strony, wzoruję się na tym: http://www.cezarywalenciuk.pl/post/2013/08/04/ASPNET-MVC.aspx. Klikam przycisk, ale nic się nie dzieje.
Kontroler

        public JsonResult GetJsonAllQuizzes()
        {
            var lOfQuizzes = quizRepository.GetQuizzes().ToList();
            return Json (lOfQuizzes, JsonRequestBehavior.AllowGet);

        }
 

Widok:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}




@{
    ViewBag.Title = "Index";
}
<p>
    @model WebQuiz.Models.QuizModel

    @using (Html.BeginForm("Index", "Home"))
    {

        <h2>
            Wybierz test:
        </h2>
        @Html.DropDownList("qId", Model.QuizListModel, new { @style = "width:200px;", @id = "myDropdownlist" })
        <input type="submit" value="Submit" id="mySubmit" />
        <br />
        <div id="mySelected">
            <br />Wybrany test:
        </div>

        <input id="btnGetQuizzes" type="button" value="Get Quizzes" />
        <div>
            <div id="ajaxQuizzes">
                Z ajax
            </div>
        </div>

    }
    @section Scripts{
        <script type="text/javascript">

            $(document).ready(function () {
                $('#btnGetQuizzes').click(function () {
                    $.getJSON("/Test/GetJsonAllQuizzes", null, function (data) {
                        var div = $('#ajaxQuizzes');
                        div.html("<br/> " + "Persons received from server: " + "<br/>");
                        $.each(data, function (i, item) {
                            printPerson(div, item);
                        });
                    });
                });
            });

            function printPerson(div, item) {
                div.append("<br/>" + "FirstName: " + item.Title + ", LastName: " + item.$1);
                $.each(item.Addresses, function (i, addr) {
                    printAddress(div, addr);
                });
            }

            function printAddress(div, item) {
                div.append("<br/>" + "   " + "City: " + item.Line1);
            }
        </script>
    }

</p>
 

Wpisałem w adresie//localhost:50021/Test/GetJsonAllQuizzes dostaję błąd:

 
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Quiz_D10A869B9E040C511B0CF90B8C18896A0B7D9B0E2365EC814E8769BCC111EB61'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Quiz_D10A869B9E040C511B0CF90B8C18896A0B7D9B0E2365EC814E8769BCC111EB61'.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Quiz_D10A869B9E040C511B0CF90B8C18896A0B7D9B0E2365EC814E8769BCC111EB61'.]
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +2616
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +371
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +819
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +2834
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +371
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +186
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +2782
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +371
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +819
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +2834
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +371
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +186
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +2782
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +371
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat) +57
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +83
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj) +44
   System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +817
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651688
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Z repozytorium:

 
        public IEnumerable<Quiz> GetQuizzes()
        {
            return context.Quizzes.ToList();
        }
2

Myślę, że kluczowe są te słowa: A circular reference was detected while serializing an object of type. Pewno klasa Quiz ma np. właściwość typu Answer, która z kolei ma właściwość wskazującą na Quiz.

0

Pewnie chodzi o kolekcję pytań. No, ale na otrzymanie takiego obiektu pewnie też jest jakiś sposób?

namespace WebQuiz.Models
{
    public class Quiz
    {
        public int QuizId { get; set; }
        public virtual ICollection<Question> Questions { get; set; }

        [Display(Name = "Nazwa:")]
        public string Title { get; set; }

        [Display(Name = "Kategoria:")]
        public string Category { get; set; }

        //public int Score { get; set; }
        //public DateTime? StartTime { get; set; }
        //public TimeSpan? Duration { get; set; }
        //public DateTime? EndTime { get; set; }
    }
}
 

Znalazłem rozwiązanie, tylko podobno lazy loading wtedy się traci.

context.Configuration.ProxyCreationEnabled = false;
 

1 użytkowników online, w tym zalogowanych: 0, gości: 1