Chaka
Chaka

Reputation: 1541

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

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

        }

Upvotes: 2

Views: 17118

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

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.

Upvotes: 7

Related Questions