所以我正在建立一个图书搜索页面,其他一切正常(按标题,作者等搜索),但我无法弄清楚如何通过我们的数据库中的int的唯一编号进行搜索 - 我尝试了几件事比如转换为int32,将IDnumber转换为字符串等但仍无法找到解决方案
参数:
<defineStatements>
<defineStatement>_binary_payload w9.gzdio</defineStatement>
<defineStatement>_binary_filedigest_algorithm 1</defineStatement>
</defineStatements>
查看代码:
public ActionResult Index(int IDnumber, string LnameString, string FnameString, string bookGenre,string searchString)
{
//LINQ query to select books
var books = from m in db.Book
select m;
//ID Number
if (IDnumber != null)
/* the if statement gives the following warning which i cannot resolve: the result of the expression is always 'true' since a value of type 'int' is never equal to null of type int?*/
{
books = books.Where(x => x.BookID == IDnumber);
}
...
}
确切错误:
参数字典包含参数的空条目 'IDnumber'为方法的非可空类型'System.Int32' 'System.Web.Mvc.ActionResult Index(Int32,System.String, System.String,System.String,System.String)'in 'SafariBooksGroup15.Controllers.BooksController'。可选的 参数必须是引用类型,可空类型或声明为 一个可选参数。参数名称:参数
答案 0 :(得分:2)
您可以int?
使用IDnumber
并将其包含在搜索中,如果它有价值。
public ActionResult Index(int? IDnumber, string LnameString, string FnameString, string bookGenre,string searchString)
{
//LINQ query to select books
var books = from m in db.Book
select m;
//ID Number
if (IDnumber.HasValue)
{
books = books.Where(x => x.BookID == IDnumber.Value);
}
...
}
另外,如果您正在寻找一种简单且可扩展的搜索模式,我建议您将问题分开并使用业务逻辑类和搜索模型来实现这样的操作方法:
public ActionResult Index(BookSearchModel searchModel)
{
var business = new BookBusinessLogic();
var model = business.GetBooks(searchModel);
return View(model);
}
下面的答案描述并实现了这样的模式: