【发布时间】:2015-08-29 17:40:45
【问题描述】:
这是我的控制器代码:
public ActionResult Index(string priceMin, string priceMax)
{
lstEventType = HttpRuntime.Cache["EventType"] as List<string>;
if (lstEventType == null || !lstEventType.Any())
{
lstEventType = new List<string>();
lst = artistModel.fillDropDown();
lstEventType = lst.Where(p => p.lookupType == "EventType").Select(q => q.lookupValue).ToList();
HttpRuntime.Cache["EventType"] = lstEventType;
}
ViewData["EventType"] = lstEventType;
artistList = artistModel.displayArtist();
if (!String.IsNullOrEmpty(priceMin))
{
aSession.priceMin = priceMin;
ViewData["priceMin"] = priceMin;
artistList = artistList.Where(p => (string.IsNullOrEmpty(p.strHiddenCost) ? 0 : Convert.ToInt32(p.strHiddenCost)) >= Convert.ToInt32(priceMin)).ToList();
}
if (!String.IsNullOrEmpty(priceMax))
{
aSession.priceMax = priceMax;
ViewData["priceMax"] = priceMax;
artistList = artistList.Where(p => (string.IsNullOrEmpty(p.strHiddenCost) ? 0 : Convert.ToInt32(p.strHiddenCost)) <= Convert.ToInt32(priceMax)).ToList();
}
return View(artistList);
}
如果这个艺术家列表返回非值,那么我没有收到任何错误。但是,如果艺术家列表返回 null,则视图中的以下代码部分将引发异常。我无法弄清楚这个艺术家列表如何影响 viewdata["EventType"]。
下面是我的代码
@{
List<string> EventTypes = ViewData["EventType"] as List<string>;
foreach (string eventType in EventTypes)
{
<li><a> <span class="pull-right"></span>@eventType</a></li>
}
}
在遍历此循环时,我遇到了索引超出范围异常。如果我的控制器向该视图返回一个非空列表,那么它工作正常。但是如果控制器返回空列表来查看这个迭代失败。
【问题讨论】:
-
也许您的 ViewData 中没有“EventType”条目
-
我在 viewdata 中得到 3 行。
-
您显示的代码中没有任何内容可以解决该错误。调试你的代码!而且您的 html 无效(
li元素不能是em元素的子元素) -
这个 em 只是为了这个 stackoverflow 。
和 标签实际上并没有出现在我的代码中。
标签: c# list asp.net-mvc-4 foreach controller