我有:
IEnumerable<CustomModel> model = //some joins and select here;
我该怎么做?
if(!String.IsNullOrEmpty(keyword))
{
return View(model.Where(m => m.Description.Contains(keyword) ||
m.Title.Contains(keyword)).ToList());
}
return View(model.ToList());
如果你想知道,这段代码不起作用。我尝试做的只是返回包含搜索关键字的项目。 这是错误:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in
the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Line 132: if(!String.IsNullOrEmpty(search_idea))
Line 133: {
Line 134: return View(model.Where(m => m.Description.Contains(search_idea) ||
Line 135: m.Title.Contains(search_idea)).ToList());
Line 136: }
提前致谢。
答案 0 :(得分:1)
我在这段代码中看到了两个问题。
首先,请考虑这里keyword
可能区分大小写的事实,您应该更改代码以进行搜索而不考虑区分大小写。
if(!String.IsNullOrEmpty(keyword))
{
return View(model.Where(m =>
m.Description.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1 ||
m.Title.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1)
.ToList());
}
return View(model.ToList());
其次,请确保m.Description
和m.Title
不为空,因为调用null.IndexOf
或null.Contains
会导致NullReferenceException
:
if(!String.IsNullOrEmpty(keyword))
{
return View(model.Where(m =>
(m.Description ?? "").IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1 ||
(m.Title ?? "").IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1)
.ToList());
}
return View(model.ToList());