1
foreach (var i in Model.Items)
{
        string s = "abc" + i.Name;
}

上面的代码给了我 InvalidOperationException,消息序列不包含任何元素。

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

1 回答 1

-2

在使用 ASP 或 MVC + SilverLight 时,我不建议使用 First() 或 FirstOrDefault()。

搜索 .First(); 或 .FirstOrDefault() 并添加 -> .DefaultIfEmpty();

于 2013-07-22T10:53:22.537 回答