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

[Solved] ForeignKey Property Causing Crash

2 Answers 43 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.
Gavin
Top achievements
Rank 1
Gavin asked on 03 Feb 2012, 02:02 AM
I seem to be having an issue with the ForeignKey property on the MVC Grid (using 2011.3.1306). I am using Entity Framework code first, I couldn't figure out the issue but have stripped everything back and created some test classes and a quick controller and view that show the issue and am able to re-produce the error. I will put in a project if the trace at the bottom is not enough to go on. It seems if you reference the child table and id in the following format 
columns.ForeignKey(h => h.Child.Id ....
then this causes a crash where child is a related entity (I do this for Entity Framework Code First), if however the link is done as
columns.ForeignKey(h => h.ChildId
then everything is ok, I have changed the way the tables link for the last example to get it working. I probably need to include an actual project with this all in as is difficult to explain, will have more time tomorrow to do this. I have followed the ForeignKey grid example and copied over the GridForeignKey.cshtml to my editortemplates folder but noticed in debug that the crash occurs before the template gets called.

The classes I have that will cause the crash are :

Parent
namespace Hire.Model
{
  public class TestModel
  {
    public int Id { get; set; }
 
    public string Description { get; set; }
 
    public TestChildModel Child { get; set; }
  }
}

Child
namespace Hire.Model
{
  public class TestChildModel
  {
    public int Id  { get; set; }
 
    public string Name { get; set; }
  }
}


Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Hire.Model;
using Telerik.Web.Mvc;
 
namespace Hire.Web.Controllers
{
  public class TestController : Controller
  {
 
    public ActionResult Index()
    {
      var childs = new List<TestChildModel>
                     {
                       new TestChildModel() {Id = 1, Name = "Child One"},
                       new TestChildModel() {Id = 2, Name = "Child Two"},
                       new TestChildModel() {Id = 3, Name = "Child Three"}
                     };
 
      ViewData["childs"] = childs;
 
      return View();
    }
 
    [GridAction]
    public ActionResult AjaxCall()
    {
 
      List<TestModel> names = new List<TestModel>
                                {
                                  new TestModel(){Id = 1, Description = "Gavin", Child = new TestChildModel(){Id = 1}},
                                  new TestModel(){Id = 2, Description = "Liz", Child = new TestChildModel(){Id = 2}}
                                };
 
      return View(new GridModel(names));
    }
 
    [HttpPost]
    [GridAction]
    public ActionResult Edit(TestModel testModel)
    {
      List<TestModel> names = new List<TestModel>
                                {
                                  new TestModel(){Id = 1, Description = "Gavin", Child = new TestChildModel(){Id = 1}},
                                  new TestModel(){Id = 2, Description = "Liz", Child = new TestChildModel(){Id = 2}}
                                };
 
      return View(new GridModel(names));
    }
  }
}

View
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <title>Index</title>
       @(Html.Telerik().StyleSheetRegistrar()
        .DefaultGroup(group => group.Add("telerik.common.css")
        .Add("telerik.sitefinity.css")))
</head>
<body>
    <div>
     @(Html.Telerik().Grid<Hire.Model.TestModel>()
        .Name("Grid")
        .DataKeys(keys => keys.Add(c => c.Id))
        .Columns(columns =>
        {
            columns.Bound(o => o.Id).Width(100);
            columns.ForeignKey(h => h.Child.Id, (IEnumerable<Hire.Model.TestChildModel>)ViewData["childs"], "Id", "Name") ;
            columns.Command(x => x.Edit());
        })
        .DataBinding(dataBinding => {
          dataBinding.Ajax().Select("AjaxCall", "Test").Update("Edit", "Test");
        })
        .Pageable()
        .Sortable()
        .Scrollable()
        .Groupable()
        .Filterable()
)
 
@(Html.Telerik().ScriptRegistrar())
 
    </div>
</body>
</html>

Error Message
[NullReferenceException: Object reference not set to an instance of an object.]
   lambda_method(Closure , TestModel ) +87
   Telerik.Web.Mvc.UI.GridForeignKeyColumn`2.AppendSelectList(IDictionary`2 viewData, Object dataItem) in f:\108\Griffin\Current Full\Sources\Source\Telerik.Web.Mvc\UI\Grid\Columns\GridForeignKeyColumn.cs:88
   Telerik.Web.Mvc.UI.Html.GridForeignKeyEditorForCellBuilder`2.AppendCellContent(IHtmlNode td, Object dataItem) in f:\108\Griffin\Current Full\Sources\Source\Telerik.Web.Mvc\UI\Grid\Html\GridForeignKeyEditorForCellBuilder.cs:22
   Telerik.Web.Mvc.UI.Html.GridDataCellBuilderBase.CreateCell(Object dataItem) in f:\108\Griffin\Current Full\Sources\Source\Telerik.Web.Mvc\UI\Grid\Html\GridDataCellBuilderBase.cs:38
   Telerik.Web.Mvc.UI.<>c__DisplayClass46.<InitializeEditors>b__42(GridColumnBase`1 column) in f:\108\Griffin\Current Full\Sources\Source\Telerik.Web.Mvc\UI\Grid\Grid.cs:1249
   Telerik.Web.Mvc.Extensions.EnumerableExtensions.Each(IEnumerable`1 instance, Action`1 action) in f:\108\Griffin\Current Full\Sources\Source\Telerik.Web.Mvc\Extensions\EnumerableExtensions.cs:61
   Telerik.Web.Mvc.UI.Grid`1.InitializeEditors() in f:\108\Griffin\Current Full\Sources\Source\Telerik.Web.Mvc\UI\Grid\Grid.cs:1245
   Telerik.Web.Mvc.UI.Grid`1.WriteHtml(HtmlTextWriter writer) in f:\108\Griffin\Current Full\Sources\Source\Telerik.Web.Mvc\UI\Grid\Grid.cs:656
   Telerik.Web.Mvc.UI.ViewComponentBase.ToHtmlString() in f:\108\Griffin\Current Full\Sources\Source\Telerik.Web.Mvc\UI\ViewComponentBase.cs:215
   Telerik.Web.Mvc.UI.ViewComponentBuilderBase`2.ToHtmlString() in f:\108\Griffin\Current Full\Sources\Source\Telerik.Web.Mvc\UI\ViewComponentBuilderBase.cs:154
   Telerik.Web.Mvc.{Dynamic}.GridBuilder`1[[Hire.Model.TestModel, Hire.Model, Version=1.0.0.0\, Culture=neutral\, PublicKeyToken=null\]\].IHtmlString.ToHtmlString() +31
   System.Web.HttpUtility.HtmlEncode(Object value) +38
   System.Web.WebPages.WebPageBase.Write(Object value) +64
   ASP._Page_Views_Test_Index_cshtml.Execute() in c:\Users\GAVIN\Documents\Visual Studio 2010\Projects\Hire\Hire.Web\Views\Test\Index.cshtml:16
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81
   System.Web.WebPages.StartPage.RunPage() +19

2 Answers, 1 is accepted

Sort by
0
Rosen
Telerik team
answered on 03 Feb 2012, 10:48 AM
Hello Gavin,

The error you have described is caused by the fact that when grid's ajax editing feature is enabled, a default instance of the assign model type is used to create the editor templates, which are then serialized to the client and used during editing. However, in your case as the by default when created TestModel's Child property will be null an error will be thrown, when the Child.Id field is accessed.

However, we managed to address this limitation and this scenario should be covered with the next official release of the library. Meanwhile, as temporary workaround you may consider changing the model class to instantiate an empty Child object:
 

public class TestModel
{
    public TestModel()
    {
        Child = new TestChildModel();
    }
 
    public int Id { get; set; }
 
    public string Description { get; set; }
 
    public TestChildModel Child { get; set; }
}
All the best,
Rosen
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now
0
Gavin
Top achievements
Rank 1
answered on 03 Feb 2012, 12:45 PM
Hi Rosen

Yes just tested your workaround and that works perfectly and solves the issue.

Thanks very much.

Gavin
Tags
Grid
Asked by
Gavin
Top achievements
Rank 1
Answers by
Rosen
Telerik team
Gavin
Top achievements
Rank 1
Share this question
or