asp.net-mvc-3 - MVC 3 异常 : The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System. Web.Mvc

标签 asp.net-mvc-3 exception nullpointerexception asp.net-mvc-routing

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

不确定出了什么问题?

我的 Controller :

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

        }

最佳答案

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

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

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

如果您要生成 anchor ,请确保有一个 id:

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

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

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

public ActionResult Agency(int? id)

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

关于asp.net-mvc-3 - MVC 3 异常 : The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System. Web.Mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15344385/

相关文章:

asp.net-mvc-3 - 如何为下拉列表使用数据注释?

c# - 在某些情况下禁用 Required 验证属性

java - Android Java - 无法捕获异常

android - 在其他 Activity 中使用 On Button Click Listener 时出错

asp.net - MVC3 - 所有路由都在本地工作,但不能远程工作

linq - MVC3 Razor @Html.DropDownListFor

Ruby "defined?"运算符工作错误?

java - 如何模拟 JestClient、elasticSearch

java - 为什么我的字符串初始化会抛出 NullPointerError?

java - 空指针异常java