Foreign key not appearing in View

199 Views Asked by At

Can anyone please assist,i have a model that contains a foreign key(ProductCategory).i am trying to call the values of the foreign key but they are not appearing in the view,when i place a breakpoint in the controller all fields appear successful in the raw results view but it seems they are not being passed to the view.

N.B i am using dev express to generate views

 public class Product
    {
        public int Id { get; set; }
        public int productCode { get; set; }
        public double price { get; set; }
        public int ProductCategoryId { get; set; }
        public virtual ProductCategory ProductCategory { get; set; }
        public Stock itemNo { get; set; }
    }
  [HttpGet]
        public async Task<IActionResult> Get(DataSourceLoadOptions loadOptions) {
            var product = _context.Product.Select(i => new {
                i.Id,
                i.productCode,
                i.price,
                i.ProductCategoryId,
                i.ProductCategory.categoryDescr      
            });

            return Json(await DataSourceLoader.LoadAsync(product, loadOptions));
        }
@{
    ViewData["Title"] = "Products";
}

<h2 class="content-block">Products</h2>

@(Html.DevExtreme().DataGrid<DevExtremeAspNetCoreApp1.Models.Product>()
    .DataSource(ds => ds.Mvc()
        .Controller("Products")
        .LoadAction("Get")
        .InsertAction("Post")
        .UpdateAction("Put")
        .DeleteAction("Delete")
        .Key("Id")
    )
    .RemoteOperations(true)
    .Columns(columns => {

        columns.AddFor(m => m.productCode);

        columns.AddFor(m => m.price);

        columns.AddFor(m => m.ProductCategoryId);

        columns.AddFor(m => m.ProductCategory.categoryDescr);
    })
    .Editing(e => e.Mode(GridEditMode.Popup)
        .AllowAdding(true)
        .AllowUpdating(true)
        .AllowDeleting(true)
        .Popup(p=>p
               .Title("Product")
               .ShowTitle(true)
               .Width(500)
               .Height(525)
              )
    )

    .Export(e => e.Enabled(true))
)

2

There are 2 best solutions below

0
Serge On

Try this:

 var product = _context.Product.Select(i => new {
                i.Id,
                i.productCode,
                i.price,
                i.ProductCategoryId,
                ProductCategoryDesc=i.ProductCategory.categoryDescr      
            });

.....

 columns.AddFor(m => m.ProductCategoryDesc);
0
Tumo Maraisane On

turns i was passing an anonymous type,correct approach should be:

Controller

  public async Task<IActionResult> Get(DataSourceLoadOptions loadOptions) {
            var product = _context.Product.Select(i => new {
                i.Id,
                i.productCode,
                i.price,
                i.ProductCategoryId,
                i.ProductCategory
            });

View:

 columns.AddFor(m => m.ProductCategory.Id);