[英]How to handle null exception for column values returned from controller in webgrid?
I am developing an MVC application in which the Webgrid is used to show table columns.我正在开发一个 MVC 应用程序,其中 Webgrid 用于显示表列。 I have One primary table named Item and secondary table named Category.
我有一个名为 Item 的主表和名为 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.
我正在尝试将 Item 表的列绑定到视图的 Webgrid 中,但在绑定外部表(类别)列时在 webgrid 内部出现异常。
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
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在 webgrid 内部查看我有
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.您可以在视图中看到我正在处理空异常,但它仍然在视图中为 Item.Category.name 生成异常,其中 Item.id 绑定没有任何问题。
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),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.