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
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),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.