2

我的应用程序似乎运行良好,但我在 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.

不知道出了什么问题?

我的控制器:

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

                return View(agency);
        }

我的路线:

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

        }
4

1 回答 1

7

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

确保当您请求此操作时,您id在 url 中指定了一个有效的:

http://example.com/somecontroller/agency/123

如果您正在生成锚点,请确保有一个 id:

@Html.ActionLink("click me", "agency", new { id = "123" })

如果您要发送 AJAX 请求,还要确保 id 存在于 url 中。

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

public ActionResult Agency(int? id)

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

于 2013-03-11T17:06:50.583 回答