Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Tags:

c#

asp.net-mvc

You are expecting an id parameter in your URL but you aren't supplying one. Such as:

http://yoursite.com/controller/edit/12
                                    ^^ missing

in your WebApiConfig >> Register () You have to change to

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }

Here the routeTemplate, is added with {action}


This error means that the MVC framework can't find a value for your id property that you pass as an argument to the Edit method.

MVC searches for these values in places like your route data, query string and form values.

For example the following will pass the id property in your query string:

/Edit?id=1

A nicer way would be to edit your routing configuration so you can pass this value as a part of the URL itself:

/Edit/1

This process where MVC searches for values for your parameters is called Model Binding and it's one of the best features of MVC. You can find more information on Model Binding here.


Is the action method on your form pointing to /controller/edit/1?

Try using one of these:

// the null in the last position is the html attributes, which you usually won't use
// on a form.  These invocations are kinda ugly
Html.BeginForm("Edit", "User", new { Id = Model.Id }, FormMethod.Post, null)

Html.BeginForm(new { action="Edit", controller="User", id = Model.Id })

Or inside your form add a hidden "Id" field

@Html.HiddenFor(m => m.Id)

You get that error because ASP.NET MVC cannot find an id parameter value to provide for the id parameter of your action method.

You need to either pass that as part of the url, ("/Home/Edit/123"), as a query string parameter ("/Home/Edit?id=123") or as a POSTed parameter (make sure to have something like <input type="hidden" name="id" value="123" /> in your HTML form).

Alternatively, you could make the id parameter be a nullable int (Edit(int? id, User collection) {...}), but if the id were null, you wouldn't know what to edit.


I also had same issue. I investigated and found missing {action} attribute from route template.

Before code (Having Issue):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

After Fix(Working code):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );