MVC 3异常:参数字典包含方法'System.Web.Mvc'的非可空类型'System.Int32'的参数'id'的空条目

Cha*_*aka 2 exception nullpointerexception asp.net-mvc-routing asp.net-mvc-3

我的应用程序似乎运行正常,但我一直在log4net日志中获得这些异常:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Agency(Int32)' in 'COPSGMIS.Controllers.QuestionController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Run Code Online (Sandbox Code Playgroud)

不确定什么是错的?

我的控制器:

 public ActionResult Agency(int id)
        {
                QuestionDAL qd = new QuestionDAL();
                var agency = qd.GetAgencyDetails(id);
                agency.Reviews = qd.GetAgencyReviews(id);

                return View(agency);
        }
Run Code Online (Sandbox Code Playgroud)

我的路线:

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

        }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 6

如果您尝试调用此控制器操作并且未id在路径部分或查询字符串参数中指定任何一个,则会引发此错误.由于控制器操作采用id作为参数,因此应确保始终指定此参数.

确保在您请求此操作时,您已id在网址中指定了有效内容:

http://example.com/somecontroller/agency/123
Run Code Online (Sandbox Code Playgroud)

如果要生成锚点,请确保有一个id:

@Html.ActionLink("click me", "agency", new { id = "123" })
Run Code Online (Sandbox Code Playgroud)

如果您要发送AJAX请求,还要确保该URL存在于URL中.

另一方面,如果参数是可选的,则可以使其成为可以为空的整数:

public ActionResult Agency(int? id)
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,您将不得不处理未指定参数值的情况.