“参数字典包含不可为空类型的参数的 null”

本文关键字:参数 类型 null 字典 包含不 | 更新日期: 2023-09-27 18:32:19

我在运行时收到 id 的空错误。这是我的所有部分。

这是我的 DAL,项目数据库

 public static List<Product> IsOrganic(int lotid)
    {
        using (var db = new ProductDB())
        {   //Selects from database in SQL what we need
            //IsDamaged is Organic, and bool for true/false for food
            DbCommand cmd = db.GetSqlStringCommand("SELECT * FROM PRODUCTS WHERE ORGANIC = 1");

            return FillList(db.ExecuteDataSet(cmd));
        }
    }

这是我的经理

public List<Product> IsOrganic(int lotid)
    {

        return ProductDB.IsOrganic(lotid);

    }

这是我的控制器

 public ActionResult Organic(int id)//Store/Organic
    {
        ProductManager mgr = new ProductManager();
        var list = mgr.IsOrganic(id);
        return View(list);
    }

另外,这是我的全球

  public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

“参数字典包含不可为空类型的参数的 null”

如果使用 C# 4,请使用可选参数的默认值

public ActionResult Organic(int id = 0)//Store/Organic
{
    ProductManager mgr = new ProductManager();
    var list = mgr.IsOrganic(id);
    return View(list);
}

如果仅使用 C# 3,则对可选参数使用默认值属性

public ActionResult Organic(
      [System.ComponentModel.DefaultValue(0)] int id) //Store/Organic
{
    ProductManager mgr = new ProductManager();
    var list = mgr.IsOrganic(id);
    return View(list);
}

但我想知道你为什么以这种方式调用有机方法,即没有参数。

如果要测试应用商店控制器的自然操作是否正常工作,请在 url 中键入以下内容:

http://localhost/Store/Organic/7

或者这个:

http://localhost/Store/Organic?id=7

如果您为商店控制器的 Organic 操作的参数 ID 使用了自定义名称,请说 organicId:

public ActionResult Organic(int organicId = 0) //Store/Organic?organicId=7
{
    ProductManager mgr = new ProductManager();
    var list = mgr.IsOrganic(id);
    return View(list);
}

,此网址将不起作用:http://localhost/Store/Organic/7

这不会有运行时错误,但 organicId 值不会被传递值,因此将始终具有 0 的值

,您必须改用以下内容:http://localhost/Store/Organic?organicId=7

顺便问一下,运行时错误从何而来?点击链接后?尝试将鼠标悬停在该链接上并查看浏览器的状态栏,您的 URL 必须符合以下内容:http://localhost/Store/Organic/7 或此 http://localhost/Store/Organic?id=7。

如果看起来不是这样,请将您的操作链接更改为以下内容:

@Html.ActionLink("Store", "Organic", new {id = 7})

或者,如果您使用的是纯 HTML:

<a href="Store/Organic/7">

或者这个:

<a href="Store/Organic?id=7">