1

I am developing an MVC application in which the Webgrid is used to show table columns. I have One primary table named Item and secondary table named Category. I am trying to bind Item table's columns into Webgrid of a View but getting exception inside webgrid while binding foreign table(Category) column.

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException

Model

public class ItemModel   
{  
    public long id { get; set; }
    public Nullable<long> category_id { get; set; }          
    public virtual Category Category { get; set; }   
}

Controller

List<ItemModel> lstItemModel = new List<ItemModel>();
List<Item> lstItemss = db.Items.ToList();
lstItemss.ForEach(x =>
{
    ItemModel stuModel = new ItemModel();
    stuModel.id= x.id;
    stuModel.Category = x.Category;
    lstItemModel.Add(stuModel);
});
return View(lstItemModel);

View inside webgrid I have

dataGrid.Column("Category", "Category", format: (Item) => string.IsNullOrEmpty(Item.Category.name)?string.Empty:Item.Category.name)

You can see in the view I am handing null exception but still it generates exception in view for Item.Category.name where as Item.id gets bind without any issue.

Thanks a lot

2
  • in debug mode look the value of Item.Category, and then share with us Commented Feb 2, 2017 at 7:52
  • You not handling the case when Category is null - string.IsNullOrEmpty(Item.Category.name) will throw an exception if the value of Category is null because you cannot access the name proprty of null) Commented Feb 2, 2017 at 7:52

1 Answer 1

1

Thanks for the comments guys. Resolved the issue with this change that worked like charm.

Instead of this

string.IsNullOrEmpty(item.Category.name)

use this

(item.Category!= null)

so finally my view modified to

dataGrid.Column("Category", "Category", format: (Item) => (Item.Category==null)?string.Empty:Item.Category.name),
Sign up to request clarification or add additional context in comments.

1 Comment

Or you could just do stuModel.Category = x.Category ?? new Category() and simplify the code in the view

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.