2015-09-04 40 views
-1

我想通過FirstName或Lastname進行搜索。如果搜索爲空,我希望列表顯示每條記錄。我碰到一個錯誤'|不能應用於'bool'和'string''類型的操作數。mvc ||不能應用於'bool'和'string'類型的操作數

這裏是我的索引控制器

[Authorize(Users="aaron")] 
public class personController : Controller 
{ 
    private dumb_so_dumbEntities db = new dumb_so_dumbEntities(); 

    // GET: /person/ 
    public ActionResult Index(string searchBy, string search) 
    { 

     if (searchBy == "FirstName") 
     { 
      return View(db.Persons.Where(x => x.FirstName.StartsWith(search) || search == null).ToList()); 
     } 
     else 
     { 
      return View(db.Persons.Where(x => x.LastName.StartsWith(search) || search == null).ToList()); 
     } 

    } 

另外,我有一個額外的問題。如果我想添加額外的搜索功能,但它是一個int(名稱爲P_Id)。我怎麼能把所有三個(一個int和兩個字符串)放在一起? 我也嘗試做了

else if (searchBy == "P_Id") 

它踢回來的東西如int不能轉換爲字符串。

+0

您應該添加一個標籤,以你的問題說這是什麼語言(C#?)。它會幫助正確的人找到它。 –

+0

你確定你提交的代碼嗎?這在我身邊運作。錯誤是否來自其他地方? –

+0

看[this fiddle](http://ideone.com/Nde7dj)。爲了避免另一個錯誤,我將這個測試轉化爲null,否則就起作用。 –

回答

0

嘗試Contains而不是像這樣:

[Authorize(Users="aaron")] 
public class personController : Controller 
{ 
    private dumb_so_dumbEntities db = new dumb_so_dumbEntities(); 

// GET: /person/ 
    public ActionResult Index(string searchBy, string search) 
    { 

     if (searchBy == "FirstName") 
     { 
      return View(db.Persons.Where(x => x.FirstName.Contains(search) || search == null).ToList(); 
     } 
     else 
     { 
      return View(db.Persons.Where(x => x.LastName.Contains(search) || search == null).ToList(); 
     } 

    } 
} 

編輯: 關於第二個問題,你可以把你intsstrings這樣的:

string convertedInteger = intToConvert.ToString(); 

,然後做你的ìf比較

+0

'Where'函數作爲參數,而不是布爾值。這不會編譯。 –

+0

哦對,我不知道 – Celt

+0

@ X.L.Ant其實這不起作用......但謝謝! –

0

嘗試:

public ActionResult Index(string searchBy, string search) 
    { 
     if (searchBy == "FirstName") 
     { 
      return View((from o in db.Persons Where o.LastName.StartsWith(search) select o).ToList()); 
     } 
     else 
     { 
     //if searchBy not "FirstName" including null then select all data.. 
      return View((from o in db.Persons select o).ToList()); 
     } 

    } 

和:

string myValue="your_value"; 

return View((from o in db.Persons Where (o.LastName.StartsWith(search)) || (o.Name==myValue) select o).ToList()); 
相關問題