foreach (var i in Model.Items)
{
string s = "abc" + i.Name;
}
上記のコードで InvalidOperationException が返され、メッセージ Sequence contains no elements が表示されます。
Model.Items は IList 型で、2 つの要素が含まれていますが、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);
}