2015-09-04 104 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()); 
相关问题