【问题标题】:The parameter dictionary contains a null entry for parameter 'IDnumber' of non-nullable type 'System.Int32'参数字典包含不可为空类型“System.Int32”的参数“IDnumber”的空条目
【发布时间】:2015-12-03 22:59:50
【问题描述】:

所以我正在建立一个图书搜索页面,其他一切正常(按标题、作者等搜索)但我不知道如何通过我们数据库中的 int 唯一编号进行搜索——我已经尝试了几件事比如转换成int32,把ID号转成字符串等等,但还是找不到解决办法

参数:

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);
    }
...
}

查看代码:

<p>
@Html.ActionLink("Create New", "Create")

@using (Html.BeginForm("Index", "Books")){
<p>
    Genre: @Html.DropDownList("bookGenre", "All")
    Title: @Html.TextBox("SearchString") <br />
    Author First Name: @Html.TextBox("FnameString")
    Author Last Name: @Html.TextBox("LnameString") <br />
    ID Number: @Html.TextBox("IDNumber")
    <input type="submit" value="Filter" /> 
</p>
}

确切的错误:

参数字典包含参数的空条目 方法的不可为空类型“System.Int32”的“IDnumber” 'System.Web.Mvc.ActionResult 索引(Int32,System.String, System.String, System.String, System.String)' 在 'SafariBooksGroup15.Controllers.BooksController'。一个可选的 参数必须是引用类型、可为空的类型或声明为 一个可选参数。参数名称:参数

【问题讨论】:

  • books = books.Where(x => x.BookID == Convert.ToInt32(IDnumber));应该只是 books = books.Where(x => x.BookID == IDnumber) 不应该吗?
  • 哦,你是对的,对不起,我会编辑
  • IDnumber is already of type int 无需对此进行任何转换.. 花时间阅读/调试您的代码
  • 您可以将int? 用于IDnumber,如果它有价值,可以将其包含在搜索中。
  • @MethodMan Ya 抱歉,那里没有意义,但是修复它仍然不能解决问题

标签: c# asp.net .net asp.net-mvc entity-framework


【解决方案1】:

您可以将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);
}

下面的答案描述并实现了这种模式:

【讨论】:

  • 哇...如此简单的解决方案解决了让我真正困惑的事情..非常感谢!!!
  • 如果您正在寻找一个好的搜索模式,您可能会发现我的回答 here 很有帮助:)
猜你喜欢
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多