[英]Sequence contains no elements - IList<T> having items
foreach (var i in Model.Items)
{
string s = "abc" + i.Name;
}
上面的代碼給了我InvalidOperationException,其中消息Sequence不包含任何元素。
Model.Items是IList類型,它包含兩個元素,盡管它在foreach循環中給了我異常。
我在i.Name上應用了watch,它顯示了一個值,但是當執行foreach循環內的行時,它給出了異常。
有什么問題?
堆棧跟蹤
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at ASP._Page_Views_Country_Hotels_cshtml.Execute() in d:\app\myController\items.cshtml:line 15
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
模型類
public class ItemsViewModel
{
public Category Category { get; set; }
public IList<Item> Items { get; set; }
}
第1至15行
@model IPF.Web.Models.ItemsViewModel
@{
Layout = "_SubLayout.cshtml";
string desc = "Items of " + Model.Category.Name + ". ";
string key = "Items of " + Model.Category.Name;
}
<h1>@string.Format("{0} - Items", Model.Category.Name)</h1>
@if (Model.Items.Count > 0)
{
IList<Models.Item> items = Model.Items.ToList();//added as suggested
foreach (var i in items)
{
desc += i.Name.ToString() + " ,";//this is where I am getting exception
//some other stuff
}
}
物品類別
public class Item
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[MaxLength(300, ErrorMessage = "Max length can be 300 only.")]
[Required]
[Remote("CheckItemName", "Item", AdditionalFields = "Id")]
public string Name { get; set; }
[Required]
[MinLength(50, ErrorMessage = "Min 50 characters should be entered.")]
[DataType(DataType.MultilineText)]
[AllowHtml]
[UIHint("tinymce_jquery_full")]
public string Description { get; set; }
}
CheckItemName方法
public JsonResult CheckItemName([Bind(Prefix = "Item")]Item oItem)
{
return Json(!repository.Items.Where(c => c.Id != oItem.Id).Any(c => c.Name == oItem.Name), JsonRequestBehavior.AllowGet);
}
在使用ASP或MVC + SilverLight時,我不建議使用First()或FirstOrDefault()。
搜索.First(); 或.FirstOrDefault()並添加-> .DefaultIfEmpty();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.