0

我在 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();
    }

但为什么我得到这个错误,

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'CrMVC.Controllers.MaterialsController'. To make a parameter optional its type should be either a reference type or a Nullable type. Parameter name: parameters

任何建议...

4

2 回答 2

2

您收到错误是因为您没有将 id 传递给控制器​​方法。

你基本上有两个选择:

  1. 始终将有效的 id 传递给控制器​​方法,或者
  2. 使用整数?参数,并在调用 GetMaterial(id) 之前合并 null。

无论如何,您应该检查material. 所以:

public ActionResult Details(int? id) 
{ 
    Material material = consRepository.GetMaterial((int)(id ?? 0)); 
    if (id == null)
        return View("NotFound");
    return View(); 
}

或者(假设你总是传递一个正确的 id):

public ActionResult Details(int id) 
{ 
    Material material = consRepository.GetMaterial(id); 
    if (id == null)
        return View("NotFound");
    return View(); 
}

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

 routes.MapRoute(
     "Default",
     "{controller}/{action}/{id}",
     new { controller = "Home", action = "Index", id="" }
 );

还有一个如下所示的 URL:

http://MySite.com/MyController/GetMaterial/6  <-- id
于 2010-05-01T06:32:46.667 回答
0

这意味着参数(int id)被传递了一个空值,使用(int?id)

(在控制器中)

于 2010-05-01T06:28:33.317 回答