开发者

What does this error states in asp.net-mvc?

I have repository class in asp.net mvc which has this,

 public 开发者_如何转开发Material GetMaterial(int id)
    {
        return db.Materials.SingleOrDefault(m => m.Mat_id == id);
    }

And my controller has this for details action result,

ConstructionRepository consRepository = new ConstructionRepository();
public ActionResult Details(int id)
    {
        Material material = consRepository.GetMaterial(id);
        return View();
    }

But why i get this error,

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

Any suggestion...


You're getting the error because you're not passing an id to the controller method.

You basically have two options:

  1. Always pass a valid id to the controller method, or
  2. Use an int? parameter, and coalesce the null before calling GetMaterial(id).

Regardless, you should check for a null value for material. So:

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

Or (assuming you always pass a proper id):

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

To pass a valid id to the controller method, you need a route that looks something like this:

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

And an URL that looks like this:

http://MySite.com/MyController/GetMaterial/6  <-- id


It means the param (int id) was passed a null, use (int? id)

(in the controller)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜