![](/img/trans.png)
[英]ASP.NET MVC ArgumentNullException: Value cannot be null. (Parameter 'source')
[英]Value cannot be null. Parameter name: source in Asp.net
我收到此錯誤,我不知道如何解決。
堆棧跟蹤:
[ArgumentNullException:值不能為null。 參數名稱:source] System.Linq.Enumerable.FirstOrDefault(IEnumerable'1 source,Func'2 predicate)+4358562
E:\\ projects \\ C#\\ eCommerce \\ eCommerce.Services \\ BasketService.cs:51中的eCommerce.Services.BasketService.addToBasket(HttpContextBase httpcontext,Int32產品ID,Int32數量)
E:\\ projects \\ C#\\ eCommerce \\ eCommerce.WebUI \\ Controllers \\ HomeController.cs:34中的eCommerce.WebUI.Controllers.HomeController.AddToBasket(Int32 id)
這是代碼:
public bool addToBasket(HttpContextBase httpcontext, int productid, int quantity)
{
bool success = true;
Basket basket = GetBasket(httpcontext);
// this line throws the error
BasketItem item = basket.BasketItems.FirstOrDefault(i => i.ProductId == productid);
if (item == null)
{
item = new BasketItem()
{
BasketId = basket.BasketId,
ProductId = productid,
Quantity = quantity
};
basket.BasketItems.Add(item);
}
else
{
item.Quantity = item.Quantity + quantity;
}
baskets.Commit();
return success;
}
請幫助我,我已經被卡住了一段時間了
取消引用時始終檢查null值。 在取消引用之前,檢查一下GetBasket是否不返回null,basket.basketitems是否不為null。
不知道GetBasket()
總是返回值,我假設它可能並不總是返回值,所以我們檢查是否為null。 同樣, basket
可能不為null,而BasketItems
可能為null,因此讓我們檢查該對象是否具有任何值。
如果兩個條件都成立,那么我們繼續執行其余代碼。 如果不是,則返回false
。 您還可以在此處創建一條消息,以記錄或返回給用戶有關購物籃為空/空的信息。
public bool addToBasket(HttpContextBase httpcontext, int productid, int quantity)
{
bool success = true;
Basket basket = GetBasket(httpcontext);
// Not sure if GetBasket always returns a value so checking for NULLs
if (basket != null && basket.BasketItems != null && basket.BasketItems.Any())
{
BasketItem item = basket.BasketItems.FirstOrDefault(i => i.ProductId == productid);
if (item == null)
{
item = new BasketItem()
{
BasketId = basket.BasketId,
ProductId = productid,
Quantity = quantity
};
basket.BasketItems.Add(item);
}
else
{
item.Quantity = item.Quantity + quantity;
}
baskets.Commit();
success = true;
}
else
{
// Basket is null or BasketItems does not contain any items.
// You could return an error message specifying that if needed.
success = false;
}
return success;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.