簡體   English   中英

如何處理從 webgrid 中的控制器返回的列值的空異常?

[英]How to handle null exception for column values returned from controller in webgrid?

我正在開發一個 MVC 應用程序,其中 Webgrid 用於顯示表列。 我有一個名為 Item 的主表和名為 Category 的輔助表。 我正在嘗試將 Item 表的列綁定到視圖的 Webgrid 中,但在綁定外部表(類別)列時在 webgrid 內部出現異常。

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException

模型

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

控制器

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);

在 webgrid 內部查看我有

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

您可以在視圖中看到我正在處理空異常,但它仍然在視圖中為 Item.Category.name 生成異常,其中 Item.id 綁定沒有任何問題。

非常感謝

謝謝你們的評論。 解決了這個像魅力一樣工作的變化的問題。

而不是這個

string.IsNullOrEmpty(item.Category.name)

用這個

(item.Category!= null)

所以最后我的觀點修改為

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM