This is a migrated thread and some comments may be shown as answers.

[Solved] Grid view error "dictionary requires a model item of type 'System.Collections.Generic.IEnumerable"

3 Answers 284 Views
Grid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Carey
Top achievements
Rank 1
Carey asked on 30 Jun 2011, 03:38 AM

I am using MVC3 with Razor view engine and the Grid control.

I am using Entity Framework as a datasource and I have tried to replicate a simple Ajax bound grid with paging following the examples to no avail.  I get the following error message:

The model item passed into the dictionary is of type 'Telerik.Web.Mvc.GridModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[TelerikMvcApplication2.PROCESS_OBJECT]'.

This is my Controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TelerikMvcApplication2;
using Telerik.Web.Mvc;
using Telerik.Web.Mvc.UI;
namespace TelerikMvcApplication2.Controllers
    public class JobController : Controller
    {
        private BODS_ETL_CONTROLEntities db = new BODS_ETL_CONTROLEntities();
  
        //
        // GET: /Job/
        public ActionResult Paging(bool? pageInput, bool? nextPrevious, bool? numeric, GridPagerPosition? position, int? currentPage, bool? pageSize)
        {
            ViewData["pageInput"] = pageInput ?? false;
            ViewData["nextPrevious"] = nextPrevious ?? true;
            ViewData["numeric"] = numeric ?? true;
            ViewData["pageSize"] = pageSize ?? false;
            ViewData["position"] = position ?? GridPagerPosition.Bottom;
            ViewData["currentPage"] = currentPage ?? 1;
  
            var process_object = db.PROCESS_OBJECT.Include("PROCESS_OBJECT_TYPE");
            return View(new GridModel(process_object.ToList()));
        }
  
        [GridAction]
        public ActionResult _Paging()
        {
            var process_object = db.PROCESS_OBJECT.Include("PROCESS_OBJECT_TYPE");
            //return View(new GridModel(process_object.ToList()));
            return View(new GridModel<TelerikMvcApplication2.PROCESS_OBJECT>
            {
                Data = process_object
            });
        }
  
        [GridAction]
        public ActionResult _AjaxBinding()
        {
            var process_object = db.PROCESS_OBJECT.Include("PROCESS_OBJECT_TYPE");
            return View(new GridModel(process_object.ToList()));
  
        }
  
        public ViewResult Index()
        {
            ViewData["pageInput"] = false;
            ViewData["nextPrevious"] = true;
            ViewData["numeric"] = true;
            ViewData["pageSize"] = false;
            ViewData["position"] = GridPagerPosition.Bottom;
            ViewData["currentPage"] = 1;
            var process_object = db.PROCESS_OBJECT.Include("PROCESS_OBJECT_TYPE");
            return View(process_object.ToList());
        }
  
        //
        // GET: /Job/Details/5
  
        public ViewResult Details(int id)
        {
            PROCESS_OBJECT process_object = db.PROCESS_OBJECT.Single(p => p.OBJECT_ID == id);
            return View(process_object);
        }
  
        //
        // GET: /Job/Create
  
        public ActionResult Create()
        {
            ViewBag.OBJECT_TYPE_ID = new SelectList(db.PROCESS_OBJECT_TYPE, "OBJECT_TYPE_ID", "OBJECT_TYPE_NAME");
            return View();
        
  
        //
        // POST: /Job/Create
  
        [HttpPost]
        public ActionResult Create(PROCESS_OBJECT process_object)
        {
            if (ModelState.IsValid)
            {
                db.PROCESS_OBJECT.AddObject(process_object);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }
  
            ViewBag.OBJECT_TYPE_ID = new SelectList(db.PROCESS_OBJECT_TYPE, "OBJECT_TYPE_ID", "OBJECT_TYPE_NAME", process_object.OBJECT_TYPE_ID);
            return View(process_object);
        }
          
        //
        // GET: /Job/Edit/5
   
        public ActionResult Edit(int id)
        {
            PROCESS_OBJECT process_object = db.PROCESS_OBJECT.Single(p => p.OBJECT_ID == id);
            ViewBag.OBJECT_TYPE_ID = new SelectList(db.PROCESS_OBJECT_TYPE, "OBJECT_TYPE_ID", "OBJECT_TYPE_NAME", process_object.OBJECT_TYPE_ID);
            return View(process_object);
        }
  
        //
        // POST: /Job/Edit/5
  
        [HttpPost]
        public ActionResult Edit(PROCESS_OBJECT process_object)
        {
            if (ModelState.IsValid)
            {
                db.PROCESS_OBJECT.Attach(process_object);
                db.ObjectStateManager.ChangeObjectState(process_object, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.OBJECT_TYPE_ID = new SelectList(db.PROCESS_OBJECT_TYPE, "OBJECT_TYPE_ID", "OBJECT_TYPE_NAME", process_object.OBJECT_TYPE_ID);
            return View(process_object);
        }
  
        //
        // GET: /Job/Delete/5
   
        public ActionResult Delete(int id)
        {
            PROCESS_OBJECT process_object = db.PROCESS_OBJECT.Single(p => p.OBJECT_ID == id);
            return View(process_object);
        }
  
        //
        // POST: /Job/Delete/5
  
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            PROCESS_OBJECT process_object = db.PROCESS_OBJECT.Single(p => p.OBJECT_ID == id);
            db.PROCESS_OBJECT.DeleteObject(process_object);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
  
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


This is my view for Paging Action:

<!-- model IEnumerable<TelerikMvcApplication2.PROCESS_OBJECT> -->
  
@model IEnumerable<TelerikMvcApplication2.PROCESS_OBJECT>
@{
    ViewBag.Title = "Paging";
}
  
<h2>Paging</h2>
  
<p>
    @Html.ActionLink("Create New", "Create")
</p>
@{
      
    var pagerStyleFlags = new[] 
    
        new { Key = "pageInput", Value = GridPagerStyles.PageInput },
        new { Key = "nextPrevious", Value = GridPagerStyles.NextPrevious },
        new { Key = "numeric", Value = GridPagerStyles.Numeric },
        new { Key = "pageSize", Value = GridPagerStyles.PageSizeDropDown }
    };
  
    GridPagerStyles pagerStyles = GridPagerStyles.NextPreviousAndNumeric;
  
    foreach (var pagerStyleFlag in pagerStyleFlags)
    {
        bool pagerStyle = (bool)ViewData[pagerStyleFlag.Key];
        if (pagerStyle == true)
        {
            pagerStyles |= pagerStyleFlag.Value;
        }
        else
        {
            pagerStyles &= ~pagerStyleFlag.Value;
        }
    }
  
    var position = (GridPagerPosition)ViewData["position"];
    var currentPage = (int)ViewData["currentPage"];
  
    currentPage = Math.Max(currentPage, 1);
    currentPage = Math.Min(currentPage, 83);
}
  
@{Html.Telerik().Grid(Model)
        .Name("Job")
          
        .DataBinding(dataBinding => dataBinding.Ajax().Select( "_Paging","Job"))
        .Pageable(paging => paging.Style(pagerStyles).Position(position).PageTo(currentPage))
        .Sortable().Render();
 }

I have seen others with a similar issue but I can not spot the difference.  Any help would be greatly appreciated :-)


Thanks,

Carey

3 Answers, 1 is accepted

Sort by
0
Accepted
Atanas Korchev
Telerik team
answered on 30 Jun 2011, 08:08 AM
Hello Carey,

 I think that the error is self explanatory. Your view expects IEnumerable whereas you pass a GridModel in the controller. 

 I suggest you check the Ajax binding help article as well as the ajax binding online demo which show a working configuration of grid ajax binding.

Greetings,
Atanas Korchev
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Carey
Top achievements
Rank 1
answered on 30 Jun 2011, 09:49 PM
OK, so I played around with it to tweak the types being passed and got the initial server binding to work with the URL: http://localhost:28171/Job/Paging.

I am not sure what the type of the model should officially be compatible with however...In the View Paging.cshtml I set

 

 

<!-- model IEnumerable<TelerikMvcApplication2.PROCESS_OBJECT> -->
@using TelerikMvcApplication2
@model IEnumerable<PROCESS_OBJECT>
  
@{Html.Telerik().Grid<PROCESS_OBJECT>(Model)
        .Name("Jobs")
          
        .DataBinding(dataBinding => dataBinding.Ajax().Select( "_Paging","Job"))
        .Pageable(paging => paging.Style(pagerStyles).Position(position).PageTo(currentPage))
        .Sortable().Render();
 }

 

In the Controller JobController.cs I set:

public ActionResult Paging(bool? pageInput, bool? nextPrevious, bool? numeric, GridPagerPosition? position, int? currentPage, bool? pageSize)
       {
           ViewData["pageInput"] = pageInput ?? false;
           ViewData["nextPrevious"] = nextPrevious ?? true;
           ViewData["numeric"] = numeric ?? true;
           ViewData["pageSize"] = pageSize ?? false;
           ViewData["position"] = position ?? GridPagerPosition.Bottom;
           ViewData["currentPage"] = currentPage ?? 1;
           var process_object = db.PROCESS_OBJECT.Include("PROCESS_OBJECT_TYPE");
           //return View(new GridModel(process_object.ToList()));
           return View(process_object);
       }
         
       [GridAction]
       public ActionResult _Paging()
       {
           var process_object = db.PROCESS_OBJECT.Include("PROCESS_OBJECT_TYPE");
           //return View(new GridModel(process_object.ToList()));
           //return View(new GridModel<TelerikMvcApplication2.PROCESS_OBJECT>
           return View(new GridModel<PROCESS_OBJECT>
           {
               Data = process_object
           });
       }

HOWEVER...Whenever I click on the paging buttons, refresh button on the grid I get a "Error: requested URL returned 500 error"

I traced the requestes using HTTP Watch and the url it is building is:
http://localhost:28171/Job/_Paging.

I view the rendered grid source and I see this format as the href link for the navigation buttons:  ="/Job/Paging?Jobs-page=3"

I am assuming that this is being translated by custom JS calls to get the correct operation name specified by the view pagin parameter for the grid but it is failing.

I can manually request it via : /Job/Paging?Jobs-page=3 ...without any problems, it just doesn't work with the grid navigation buttons.
I also don;t think that requesting the URL this way is using the Ajax binding.

Any ideas what is happening here?  Seems like a simple issue and maybe I am just overlooking something.  I pretty much copied verbatum the sample code supplied.

Thanks,

Carey

0
Carey
Top achievements
Rank 1
answered on 30 Jun 2011, 10:22 PM

OK so I see this is a reported error already: http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-grid-troubleshooting.html#ServerError

You might want to check out this thread as well: http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=18663

I see the same results using HTTP Watch below.

There is a few terms that mean different things.  The solution says to change the visibility of the "association property".   When I view my model in the EDMX designer, I see "Navigation Properties".  If these are what you are referring to, then do I need to change this on all of them?  For example, the entities I see have many Navigation properties, do i change the visibility on the getter and setter on all of them or only the ones involved in the context of the query that I am passing?

Or according to the post link I pasted above, they sugest deleting the Navigation property altogether on the POK side of the relationship?  All of this seems a bit restrictive, but what do you sugest i do.

I don't really feel like writing a bunch of plumbing code again as the Troubleshooting guide sugests as that sort of defeats the purpose of using an ORM framework like EF to begin with :-)

<html>
    <head>
        <title>A circular reference was detected while serializing an object of type 'TelerikMvcApplication2.PROCESS_OBJECT'.</title>
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Lucida Console";font-size: .9em}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
        </style>
    </head>
  
    <body bgcolor="white">
  
            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
  
            <h2> <i>A circular reference was detected while serializing an object of type 'TelerikMvcApplication2.PROCESS_OBJECT'.</i> </h2></span>
  
            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
  
            <b> Description: </b>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.
  
            <br><br>
  
            <b> Exception Details: </b>System.InvalidOperationException: A circular reference was detected while serializing an object of type 'TelerikMvcApplication2.PROCESS_OBJECT'.<br><br>
  
            <b>Source Error:</b> <br><br>
  
            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code>
  
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.</code>
  
                  </td>
               </tr>
            </table>
  
            <br>
  
            <b>Stack Trace:</b> <br><br>
  
            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>
  
[InvalidOperationException: A circular reference was detected while serializing an object of type 'TelerikMvcApplication2.PROCESS_OBJECT'.]
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1478
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +126
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1311
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +502
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1355
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +502
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1355
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +126
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1311
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeDictionary(IDictionary o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +505
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1250
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat) +26
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +74
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj) +6
   System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +216
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
   System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862381
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
</pre></code>
  
                  </td>
               </tr>
            </table>
  
            <br>
  
            <hr width=100% size=1 color=silver>
  
            <b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225
  
            </font>
  
    </body>
</html>
Tags
Grid
Asked by
Carey
Top achievements
Rank 1
Answers by
Atanas Korchev
Telerik team
Carey
Top achievements
Rank 1
Share this question
or