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

主宰稳场 提交于 2019-12-08 03:30:36

问题


My application seems to run fine, but I keep getting these exceptions in log4net logs:

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.

Not sure whats going wrong?

My controller:

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

                return View(agency);
        }

My routes:

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

        }

回答1:


This error is thrown if you attempt to call this controller action and you do not specify the id either in the path portion or as query string parameter. Since your controller action takes an id as parameter you should make sure that you always specify this parameter.

Make sure that when you are requesting this action you have specified a valid id in the url:

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

If you are generating an anchor, make sure there's an id:

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

If you are sending an AJAX request, also make sure that the id is present in the url.

If on the other hand the parameter is optional, you could make it a nullable integer:

public ActionResult Agency(int? id)

but in this case you will have to handle the case where the parameter value is not specified.



来源:https://stackoverflow.com/questions/15344385/mvc-3-exception-the-parameters-dictionary-contains-a-null-entry-for-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!