MVC ||不能应用于'bool'和& # 39;字符串# 39;
本文关键字:字符串 不能 应用于 bool MVC | 更新日期: 2023-09-27 18:11:25
我想通过FirstName或Lastname进行搜索。我希望列表显示搜索为空时的每条记录。我遇到了一个错误'|不能应用于'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(name as P_Id)我如何在一个动作中把这三个(一个int和两个string)放在一起?我确实试过做一个
else if (searchBy == "P_Id")
它反作用为不能将int转换为string。
try:
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());
试试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();
}
}
}
编辑:对于第二个问题,您可以像这样将ints
转换为strings
:
string convertedInteger = intToConvert.ToString();
然后做ìf
比较