2016-11-29 52 views
1

我試圖通過傳遞給控制器​​動作作爲參數關鍵字來實現搜索,如下圖所示:在資源庫中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個觸點,我可以看到他們的時候我沒有通過查詢參數。如果你能指出爲什麼控制器操作返回一個空列表,我將不勝感激。

+0

嘗試使用,而不是查詢String.IsNullOrEmpty!= NULL –

回答

2

當你傳遞一個空字符串查詢參數,條件 if(query!=null)失敗,並低於

list = list.Where(c => c.FirstName.ToLower().Contains(query.ToLower()) 
      || c.LastName.ToLower().Contains(query.ToLower())); 

行被執行,檢查數據庫與在LastName空字符串的條目。這個條件永遠不會得到滿足,因此你的列表被一個空列表覆蓋。

2

變化if (query != null)if (!string.IsNullOrEmpty(query))

+0

問題是_why控制器動作返回一個空列表?_ –

+0

@StephenMuecke是,答案是,因爲錯的,如果聲明。 – esiprogrammer

+0

不,OP要求他們的單元測試通過(但我懷疑他們的說法是錯誤的,因爲我可以重複) –