locked
What am I missing? RRS feed

  • Question

  • User1178919836 posted

    Alright, let me start this with an explanation. I've been trying to figure out what I'm not doing right with this program for quite a few days of work time. I'm well aware of my ability is lacking, but I've hit a wall. I'm not asking for you to answer my problem completely, but pointing me in the right direction and explaining what it is I'm missing would be appreciated. Below is the code and the associated MVC4 pages.

    Controllers

    First, I have a database tied to it. If I get any responses requesting the database I can upload it, but I'm more interested in getting the code right. I'm fairly sure the database is in working order.

    Second Controller: DatabaseDAL


    using System.Linq;
    using MvcApp.Models;

    namespace MvcApp.Controllers
    {

    public class DatabaseDAL

    {
    private static BookstoreEntities BSEntity = new BookstoreEntities();

    public static IQueryable<BookOrderedModel> GetAllBooks()
    {
    var query = from b in BSEntity.Books
    join ba in BSEntity.BookAuthors on b.ISBN equals ba.ISBN
    join a in BSEntity.Authors on ba.AuthorID equals a.AuthorID
    join oi in BSEntity.OrderItems on b.ISBN equals oi.ISBN
    join o in BSEntity.Orders on oi.OrderItemID equals o.OrderItemID
    join c in BSEntity.Customers on o.CustomerID equals c.CustomerID
    select new BookOrderedModel()
    {
    ISBN = b.ISBN,
    Title = b.Title,
    Category = b.Category,
    Author = a.FName + " " + a.LName,
    Customers = c.FirstName + " " + c.LastName,
    City = c.City,
    State = c.State,
    HowMany = o.Quantity
    };

    return query;

    }
    }
    }

    Third Controller: EnumerableExtensions

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    namespace MvcApp.Controllers
    {
    public static class EnumerableExtensions
    {
    /// <summary>
    /// Converts the source sequence into an IEnumerable of SelectListItem
    /// </summary>
    /// <param name="items">Source sequence</param>
    /// <param name="nameSelector">Lambda that specifies the name for the SelectList items</param>
    /// <param name="valueSelector">Lambda that specifies the value for the SelectList items</param>
    /// <returns>IEnumerable of SelectListItem</returns>
    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(
    this IEnumerable<TItem> items,
    Func<TItem, TValue> valueSelector,
    Func<TItem, string> nameSelector)
    {
    return items.ToSelectList(valueSelector, nameSelector, x => false);
    }

    /// <summary>
    /// Converts the source sequence into an IEnumerable of SelectListItem
    /// </summary>
    /// <param name="items">Source sequence</param>
    /// <param name="nameSelector">Lambda that specifies the name for the SelectList items</param>
    /// <param name="valueSelector">Lambda that specifies the value for the SelectList items</param>
    /// <param name="selectedItems">Those items that should be selected</param>
    /// <returns>IEnumerable of SelectListItem</returns>
    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(
    this IEnumerable<TItem> items,
    Func<TItem, TValue> valueSelector,
    Func<TItem, string> nameSelector,
    IEnumerable<TValue> selectedItems)
    {
    return items.ToSelectList(
    valueSelector,
    nameSelector,
    x => selectedItems != null && selectedItems.Contains(valueSelector(x)));
    }

    /// <summary>
    /// Converts the source sequence into an IEnumerable of SelectListItem
    /// </summary>
    /// <param name="items">Source sequence</param>
    /// <param name="nameSelector">Lambda that specifies the name for the SelectList items</param>
    /// <param name="valueSelector">Lambda that specifies the value for the SelectList items</param>
    /// <param name="selectedValueSelector">Lambda that specifies whether the item should be selected</param>
    /// <returns>IEnumerable of SelectListItem</returns>
    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(
    this IEnumerable<TItem> items,
    Func<TItem, TValue> valueSelector,
    Func<TItem, string> nameSelector,
    Func<TItem, bool> selectedValueSelector)
    {
    //return from item in items
    // let value = valueSelector(item)
    // select new SelectListItem
    // {
    // Text = nameSelector(item),
    // Value = value.ToString(),
    // Selected = selectedValueSelector(item)
    // };

    foreach (var item in items)
    {
    var value = valueSelector(item);

    yield return new SelectListItem
    {
    Text = nameSelector(item),
    Value = value.ToString(),
    Selected = selectedValueSelector(item)
    };
    }

    }
    }
    }

    Last Controller: HomeController

    using System;
    using System.Linq;
    using System.Web.Mvc;
    using MvcApp.AjaxResponses;
    using MvcApp.GridModels;
    using MvcApp.Models;

    namespace MvcApp.Controllers
    {
    public class HomeController : Controller
    {
    private BookstoreEntities dbEntity = new BookstoreEntities();
    private static string SelectedState;

    [HttpGet]
    public ActionResult Index()
    {
    StateModel model=new StateModel();

    return View(model);
    }

    public JsonResult PostSelectedState(BookOrderedModel State)
    {
    var response = new DefaultAjaxResponse();

    try
    {
    var selectedStr=string.Format("The selected State is {0}", State.State);
    response.AddFeedback(DefaultAjaxResponse.AjaxResponseStatusType.Success, selectedStr);
    return Json(response);
    }
    catch (Exception)
    {
    response.AddFeedback(DefaultAjaxResponse.AjaxResponseStatusType.Error, "Input was failed! ");
    return Json(response);
    }

    }

    [HttpPost]
    public ActionResult CustomersByState(FormCollection State)
    {
    BookOrderedModel model =new BookOrderedModel();
    model.State = State[0];
    SelectedState = State[0];
    return View(model);
    }


    [HttpPost]
    public ActionResult GetCustomersByState(JqGridSettings gridSettings)
    {

    int totalPages;
    int totalRecords;
    var CustomersByState = dbEntity.Customers.Where(c => c.State.Equals(SelectedState));

    var results = jqGridDataManager.GetGridData<Customer>(gridSettings, CustomersByState, out totalPages, out totalRecords);
    JqGridResult result = new JqGridResult()
    {
    Page = gridSettings.PageIndex,
    Records = totalRecords,
    Total = totalPages,
    Rows = results.ToList()
    };

    return Json(result, JsonRequestBehavior.AllowGet);
    }
    }
    }

    Model: BookOrderedModel

    namespace MvcApp.Models
    {
    public class BookOrderedModel
    {
    public string ISBN { get; set; }
    public string Title { get; set; }
    public string Category { get; set; }
    public string Author { get; set; }
    public string Customers { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public int? HowMany { get; set; }

    }
    }

    Second Model: StateModel

    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using MvcApp.Controllers;

    namespace MvcApp.Models
    {
    public class StateModel
    {
    public string State { get; set; }
    public IEnumerable<SelectListItem> StateList { get; set; }

    public StateModel()
    {
    var dbEntity = new BookstoreEntities();
    var q = dbEntity.Customers
    .OrderBy(c => c.State)
    .Select(c => new StateModel
    {
    State = c.State
    }).Distinct();

    StateList = q.ToSelectList(c => c.State, c => c.State);
    }
    }
    }

    Views: CustomersByState

    @model MvcApp.Models.BookOrderedModel

    @{
    ViewBag.Title = "CustomersByState";
    }

    @section MainHeaderContentPlaceHolder
    {
    <div>
    @Html.Partial("Header")
    </div>
    }

    <div class="admin-grid-wrapper">
    <table id="AllBooksjqGrid"></table>
    <div id="AllBooksjqGridPager"></div>
    </div>

    <script type="text/javascript">

    $(document).ready(function () {

    $("#AllBooksjqGrid").trigger("reloadGrid");

    var thisjqGrid = $('#AllBooksjqGrid').jqGrid({
    url: '/Home/GetCustomersByState',
    datatype: 'json',
    mtype: 'POST',
    caption: 'Books',
    colNames: ['ISBN', 'Title', 'Category', 'Author', 'Customers', 'City', 'State', 'HowMany'],
    colModel:
    [
    {
    name: 'ISBN',
    index: 'ISBN',
    editable: true,
    editrules: { edithidden: false },
    key: true,
    hidden: true
    },
    { name: 'Title', editable: true },
    { name: 'Category', editable: true },
    { name: 'Author', editable: true },
    { name: 'Customers', editable: true },
    { name: 'City', editable: true },
    { name: 'State', editable: true },
    { name: 'HowMany', editable: true },

    ],
    jsonReader: {
    root: "Rows",
    page: "Page",
    total: "Total",
    records: "Records",
    repeatitems: false,
    userdata: "UserData",
    id: "0"
    },
    rowNum: 5,
    rowList: [5, 10, 20],
    pager: jQuery('#AllBooksjqGridPager'),
    sortname: 'State',
    sortorder: 'asc',
    viewrecords: true,

    editurl: '/Home/SaveBooks',
    edit: {
    addCaption: 'Edit Books',
    saveData: 'Data has changed. Save changes?',
    closeAfterAdd: true,
    closeAfterEdit: true,
    closeOnEscape: true,
    viewPagerButtons: false
    },
    multiselect: false,
    autowidth: true,
    //width: 600,
    height: 'auto'
    });
    thisjqGrid.jqGrid(
    'navGrid',
    '#AllBooksjqGridPager',
    { edit: false, add: false, del: false, search: true },
    {}, // edit options
    {}, // add options
    {}, // delete options
    { closeOnEscape: true, closeAfterSearch: true, multipleSearch: true }, // search options
    {} // view options

    );
    });


    </script>

    View 2: Index

    @model MvcApp.Models.StateModel

    @{
    ViewBag.Title = "State Dropdown List";
    }

    @section MainHeaderContentPlaceHolder
    {
    <div>
    @Html.Partial("Header")
    </div>
    }

    @using (Html.BeginForm("CustomersByState", "Home"))
    {
    <fieldset style="width: 50%">
    <legend>States</legend>

    <table>
    <tr>
    <td>@Html.DropDownListFor(m => m.State, Model.StateList, "[ Select a State ]")</td>
    </tr>
    <tr>
    <td><input type="submit" value="View Books" /></td>
    </tr>
    </table>

    <p>

    </p>
    </fieldset>

    }

    <script type="text/javascript">

    $(document).ready(function () {
    $("#State").live("change", function() {
    var option = this.options[this.selectedIndex];
    var SelectedState = $(option).text();
    var State = GetState(SelectedState);
    var jsonInput = $.toJSON(State);

    $.ajax({
    url: '/home/PostSelectedState',
    type: 'POST',
    dataType: 'json',
    data: jsonInput,
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
    var messageFromServer = data.feedback[0].message;
    //alert(messageFromServer);
    },
    error: function (data) {
    alert("Fail inputing person data");
    }

    });

    });
    });

    function GetState(SelectedState) {
    return { StateName: SelectedState };
    }

    </script>

    I've got the shared views still, but above is the primary problem makers. I'm just trying to figure out even a starting point from here. I've tried multiple different methods for figuring out what's going wrong. I'll post below the errors I'm getting in the file

      • Server Error in '/' Application.


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

        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.Customer_3AB0F2EBFCDC6B7E92B788B14544A4B9A21A3DE5C7B55F9D142C89645504500C'.

        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.Customer_3AB0F2EBFCDC6B7E92B788B14544A4B9A21A3DE5C7B55F9D142C89645504500C'.]
           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) +820
           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) +820
           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) +820
           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.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) +814
           System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
           System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +74
           System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +388
           System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +72
           System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +303
           System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +155
           System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +184
           System.Web.Mvc.Async.WrappedAsyncResult`1.End() +136
           System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
           System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
           System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +40
           System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
           System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
           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.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
           System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
           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.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +45
           System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
           System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
           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() +9629296
           System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
        


        Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034            
    Not expecting miracles, but if anyone can help me figure it out it would be appreciated.
    Thursday, April 4, 2013 5:14 PM

Answers

  • User1358036820 posted

    The error says you have a "circular reference" somewhere.  This could occur if you have entity classes which look something like the following.

    public class Person
    {
    public List<Address> Address{get;set;}
    }
    public class Address
    {
    public List<Person> Person {get;set;}
    }

    As you can see the Address class points back to the Person class and that is a type of circular reference.  I suggest you take a look at your entities and see if you have any classes that look like this.

    Hope this helps.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 4, 2013 5:54 PM
  • User1358036820 posted

    I am not a EF user I have used NHibernate and other such ORM's and have had this due to what I mentioned above.  Although one other thing I would suggest is have a look at that Join you are doing, try seeing what happens if you do it one-by-one rather than all in one go and see if you can pin point the error.

    Hope that helps.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 4, 2013 7:50 PM

All replies

  • User1358036820 posted

    The error says you have a "circular reference" somewhere.  This could occur if you have entity classes which look something like the following.

    public class Person
    {
    public List<Address> Address{get;set;}
    }
    public class Address
    {
    public List<Person> Person {get;set;}
    }

    As you can see the Address class points back to the Person class and that is a type of circular reference.  I suggest you take a look at your entities and see if you have any classes that look like this.

    Hope this helps.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 4, 2013 5:54 PM
  • User1178919836 posted

    Even though I did already know that, I do appreciate the answer. This marks the first time I've needed help that someone's responded on any website. ^_^ Much appreciated.

    Thursday, April 4, 2013 6:27 PM
  • User1358036820 posted

    I am not a EF user I have used NHibernate and other such ORM's and have had this due to what I mentioned above.  Although one other thing I would suggest is have a look at that Join you are doing, try seeing what happens if you do it one-by-one rather than all in one go and see if you can pin point the error.

    Hope that helps.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 4, 2013 7:50 PM