我试图通过传递给控制器动作作为参数关键字来实现搜索,如下图所示:在资源库中MVC空查询字符串参数奇怪的行为
public ActionResult Index(string query)
{
var contacts = _unitOfWork.Contacts.GetContacts(_user.Id, query);
var viewModel = contacts.Select(Mapper.Map<Contact, ContactViewModel>);
return View("Index", viewModel);
}
GetContacts
功能如下所示:
public IEnumerable<Contact> GetContacts(int userId, string query = null)
{
var list = _context.Contacts
.Where(c => c.UserId == userId)
.OrderBy(c => c.FirstName)
.AsQueryable();
if (query != null)
list = list.Where(c => c.FirstName.ToLower().Contains(query.ToLower())
|| c.LastName.ToLower().Contains(query.ToLower()));
return list.ToList();
}
当我导航到http://localhost:50139/contacts/index?query=
时,我得到一个空列表。经过代码,显然query
参数被转换为空字符串值。 为了保证搜索的作品,我有以下的测试,他们都通过:
GetContacts_SearchByFirstName_ShouldReturnFilteredList
GetContacts_SearchByLastName_ShouldReturnFilteredList
GetContacts_SearchWithCapitalLetters_ShouldReturnFilteredList
GetContacts_SearchWithNullQuery_ShouldReturnAllContacts
特别是,下面的测试运行与空字符串,这也成功通过该功能。
[TestMethod]
public void GetContacts_SearchWithEmptyString_ShouldReturnAllContacts()
{
var contactList = new List<Contact>()
{
// Construct new contact with first and last name and associated user id.
new Contact("e", "b",_userId),
new Contact("c", "b",_userId),
new Contact("a", "b",_userId),
new Contact("d", "b",_userId)
};
_mockContacts.SetSource(contactList);
var result = _repository.GetContacts(_userId, "");
result.Count().Should().Be(4);
}
我在数据库中有3个触点,我可以看到他们的时候我没有通过查询参数。如果你能指出为什么控制器操作返回一个空列表,我将不胜感激。
尝试使用,而不是查询String.IsNullOrEmpty!= NULL –