Asp.net mvc 匿名模型的搜索项

Asp.net mvc 匿名模型的搜索项,asp.net-mvc,search,Asp.net Mvc,Search,我有: 如果您想知道,此代码不起作用。我试图做的是只返回包含搜索关键字的项目。 以下是错误: if(!String.IsNullOrEmpty(keyword)) { return View(model.Where(m => m.Description.Contains(keyword) || m.Title.Contains(keyword)).ToList()); } return V

我有:

如果您想知道,此代码不起作用。我试图做的是只返回包含搜索关键字的项目。 以下是错误:

   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:            }
其次,确保
m.Description
m.Title
不为null,因为调用
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());

条件应被否定:
!String.IsNullOrEmpty(关键字)
.Yep。讽刺的是,你说过如果有一个关键字,那么按该关键字过滤的部分应该被跳过。我的错,当我试图在这里键入它时,它是一个打字错误。我希望将来能提供准确的代码和尽可能多的细节(比如你的
NullReferenceException
)。这将确保你更快地得到更好的答案。是的,我害怕贴太多的单词,使它更难阅读。我会记住的,对不起。@user3758745无需道歉。只是想帮助你更快地得到更好的答案!
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());
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());