搜索匿名模型的项目

时间:2014-11-10 19:50:12

标签: asp.net-mvc search

我有:

   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:            }

提前致谢。

1 个答案:

答案 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.Descriptionm.Title不为空,因为调用null.IndexOfnull.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());