此错误在asp.net-mvc中表示什么?

此错误在asp.net-mvc中表示什么?,asp.net-mvc,detailsview,Asp.net Mvc,Detailsview,我在asp.net mvc中有一个存储库类 public Material GetMaterial(int id) { return db.Materials.SingleOrDefault(m => m.Mat_id == id); } 我的控制器有这个详细的动作结果 ConstructionRepository consRepository = new ConstructionRepository(); public ActionResult Det

我在asp.net mvc中有一个存储库类

 public Material GetMaterial(int id)
    {
        return db.Materials.SingleOrDefault(m => m.Mat_id == id);
    }
我的控制器有这个详细的动作结果

ConstructionRepository consRepository = new ConstructionRepository();
public ActionResult Details(int id)
    {
        Material material = consRepository.GetMaterial(id);
        return View();
    }
但是为什么我会犯这个错误

参数字典包含“CrMVC.Controllers.MaterialsController”中方法“System.Web.Mvc.ActionResult Details(Int32)”的不可为null类型“System.Int32”的参数“id”的null条目。要使参数成为可选参数,其类型应为引用类型或可为null的类型。
参数名称:参数

任何建议…

这意味着参数(int-id)被传递了一个null,use(int-id)


(在控制器中)

由于未将id传递给控制器方法,因此出现错误

您基本上有两种选择:

  • 始终将有效id传递给控制器方法,或
  • 使用int?参数,并在调用GetMaterial(id)之前合并null
  • 无论如何,您应该检查
    材料的空值。因此:

    public ActionResult Details(int? id) 
    { 
        Material material = consRepository.GetMaterial((int)(id ?? 0)); 
        if (id == null)
            return View("NotFound");
        return View(); 
    }
    
    或者(假设您始终通过正确的id):

    要将有效id传递给控制器方法,您需要一个如下所示的路由:

     routes.MapRoute(
         "Default",
         "{controller}/{action}/{id}",
         new { controller = "Home", action = "Index", id="" }
     );
    
    http://MySite.com/MyController/GetMaterial/6  <-- id
    
    以及一个如下所示的URL:

     routes.MapRoute(
         "Default",
         "{controller}/{action}/{id}",
         new { controller = "Home", action = "Index", id="" }
     );
    
    http://MySite.com/MyController/GetMaterial/6  <-- id
    
    http://MySite.com/MyController/GetMaterial/6