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

ForeignKey column not working

3 Answers 1003 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Renato
Top achievements
Rank 1
Renato asked on 08 Jan 2017, 03:06 PM

I am trying to implement a grid with a foreign key Column.

I am using your example

http://demos.telerik.com/aspnet-core/grid/foreignkeycolumn

I am trying to understand the right way to implement the editor template, unfortunately you didn't provide a full working example.

this is the error:

An unhandled exception occurred while processing the request.
ArgumentNullException: Value cannot be null.
Parameter name: items
.ctor

And this is the view

@(Html.Kendo().Grid<TraderMade.Models.Market>()
        .Name("grid")
        .Columns(columns =>
        {
            columns.Bound(c => c.Name).Width(200);
            columns.ForeignKey(p => p.CountryId, (System.Collections.IEnumerable)ViewData["countries"], "Id", "Name")
          .Title("Nazione").Width(150);
            columns.Bound(c => c.City).Title("Città").Width(150);
            columns.Bound(c => c.MIC).Title("Codice").Width(80);
            columns.Bound(c => c.WebSiteUrl).Title("Web site").Width(250);
            columns.Command(command => command.Destroy()).Width(110);
        })
        .Filterable(ftb => ftb.Mode(GridFilterMode.Menu))
        .HtmlAttributes(new { style = "height: 380px;" })
        .ToolBar(toolbar =>
        {


            toolbar.Create();
            toolbar.Save();
        })
        .Editable(editable => editable.Mode(GridEditMode.InCell))
        .Scrollable()
        .Groupable()
        .Sortable()


        .DataSource(dataSource => dataSource
            .Ajax()
            .Batch(true)
            .ServerOperation(false)
            .Events(events => events.Error("error_handler"))
        .Model(model => model.Id(p => p.Id))
        .Create("Countries_Create", "Home")
        .Read("Countries_Read", "Home")
        .Update("Countries_Update", "Home")
        .Destroy("Countries_Delete", "Home")
        ).Deferred()
)

this is the relevant part of the controller

 private void PopulateCountries()
        {
            var countries = _context.Countries.ToList();
            ViewData["countries"] = countries;
            ViewData["defaultCountry"] = countries.First();
        }


        public IActionResult Index()
        {
            PopulateCountries();
            return View();
        }

 

 public ActionResult Countries_Read([DataSourceRequest] DataSourceRequest request)
        {
            var markets = _context.Markets;
            DataSourceResult result = markets.ToDataSourceResult(request);


            return Json(result);



        }

I have read somewhere that I need to create a folder in views\shared\EditorTemplates, in this folder I have created

GridForeignKey.cshtml

@model object

@(
 Html.Kendo().DropDownListFor(m => m)
        .BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
        .ValuePrimitive(true)
)

 

here the model:

  public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public string CodeAlpha2 { get; set; }

        public string CodeAlpha3 { get; set; }
        public int CodeNumeric { get; set; }


        public ICollection<Market> Markets { get; set; }
    }

 public class Market
    {
        public int Id { get; set; }
        public string MIC { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string WebSiteUrl { get; set; }
        public string Notes { get; set; }
        public bool IsEnabled { get; set; }
        public int CountryId { get; set; }
        [ForeignKey("CountryId")]
        public Country Country { get; set; }


    }

I have tried to use ViewModel instead of model, but no matter what i write in  columns.ForeignKey  I have always the same error.

thank you for the support

 

3 Answers, 1 is accepted

Sort by
0
Konstantin Dikov
Telerik team
answered on 11 Jan 2017, 03:03 PM
Hello Renato,

The configuration seems correct and it is the same that is used in our online demo. You can also test the following example (which shows how to use a custom editor, but you can remove the EditorTemplateName and it should be the same as the demo):
On a side note, can you please elaborate if the error occurs when you try to open the cell for editing?

Looking forward to your reply.


Regards,
Konstantin Dikov
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Renato
Top achievements
Rank 1
answered on 11 Jan 2017, 09:06 PM

Hello Konstantin,

I have tried, but I have the same error when I load the view

System.ArgumentNullException occurred
  HResult=-2147467261
  Message=Value cannot be null.
Parameter name: items
  Source=Microsoft.AspNetCore.Mvc.ViewFeatures
  ParamName=items
  StackTrace:
       at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, IEnumerable selectedValues, String dataGroupField)
       at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, IEnumerable selectedValues)
       at Microsoft.AspNetCore.Mvc.Rendering.SelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, Object selectedValue)
       at Microsoft.AspNetCore.Mvc.Rendering.SelectList..ctor(IEnumerable items, String dataValueField, String dataTextField)
       at Kendo.Mvc.UI.Fluent.GridColumnFactory`1.ForeignKey[TValue](Expression`1 expression, IEnumerable data, String dataFieldValue, String dataFieldText)
       at AspNetCore._Views_Home_About_cshtml.<ExecuteAsync>b__21_0(GridColumnFactory`1 columns) in /Views/Home/About.cshtml:line 13
  InnerException: 

I have followed your advice, but something strange happens with

 ViewData["countries"] = countries.Select(e => new {
                CountryId = e.Id,
                Name = e.Name
            });

If I look with the debug in the ViewData I have an exception

Results View = The type '<>f__AnonymousType0<CountryId,Name>' exists in both 'TraderMade.exe' and 'Microsoft.AspNetCore.Hosting.dll'

maybe my project.json have something wrong?

{
  "dependencies": {
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.EntityFrameworkCore": "1.0.1",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Telerik.UI.for.AspNet.Core": "2016.3.1118"
  },


  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview2-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    },
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"


  },


  "frameworks": {
    "net461": {

    }
  },


  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },


  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },


  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

 

thank you 

renato

 

0
Konstantin Dikov
Telerik team
answered on 16 Jan 2017, 09:24 AM
Hi Reneto,

The stack trace of the error indicates that the collection that you are passing is null. Can you please ensure that the values are correctly set in the ViewData:
public ActionResult Index()
        {
            PopulateCountries();
            return View();
        }

private void PopulateCountries()
       {
           var countries = _context.Countries.ToList();
           ViewData["countries"] = countries; //the error will be thrown if contries is null
           ViewData["defaultCountry"] = countries.First();
       }

You can also try the following:
ViewData["countries"] = _context.Countries;


Regards,
Konstantin Dikov
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Tags
Grid
Asked by
Renato
Top achievements
Rank 1
Answers by
Konstantin Dikov
Telerik team
Renato
Top achievements
Rank 1
Share this question
or