31

I am building My first MVC application, I have a table in database containing 3 columns:

  1. Id → primary key
  2. Username
  3. password

When I am clicking on edit link edit a record, its throwing following exception:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'MvcApplication1.Controllers.UserController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

Here is my edit code:

public ActionResult Edit(int id, User collection)
{
    UserDBMLDataContext db = new UserDBMLDataContext();
    var q = from abc in db.User_Login_Details
            where abc.Id == id
            select abc;

    IList lst = q.ToList();

    User_Login_Details userLook = (User_Login_Details)lst[0];

    userLook.Username = collection.UserName;
    userLook.Password = collection.Password;
    db.SubmitChanges();
    return RedirectToAction("Index");                  
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • In general, this is about wrong URL you're building for edit page, to be more precisely - about id parameter of URL. Check in your browser, what URL you receiving when you have this kind of exception and please, post it here. – Dmytro Aug 05 '13 at 07:39

17 Answers17

43

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

http://yoursite.com/controller/edit/12
                                    ^^ missing
Luc
  • 5,339
  • 2
  • 48
  • 48
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • 2
    Just a FYI i know it's not the same case but had the same error so, when sending a datetime variable, be sure to put it in a correct format,if not the BE(backend) won't be recognizing the field as a valid parameter and will give you the same error.(I solved it sending datetime variable as a string and parsing it to datetime in the BE) – Matias Sep 21 '16 at 12:19
  • You are right . I am facing the same issue when passing primitive data type to Post service. it must be in url as ?id=12 – Zar E Ahmer Aug 24 '17 at 05:22
  • he's using an mvc grid so he has no control over what is passed to the edit action result. The parameters are automatically generated route values. – John Lord Dec 12 '19 at 17:04
  • @JohnLord this question is over 6 years old. The answer still applies, however. Where exactly did the OP say they were using an MVC grid? Also, how does that change the answer to the question? – Simon Whitehead Dec 12 '19 at 22:51
  • "I am making my first MVC application "... and then he said he's showing data from a table and clicking "edit" to edit a record AND it's calling an edit function in the controller with an actionresult. Now I may be wrong (he's refreshing the page afterwards) but all signs point to it. Also i didn't notice it was so old. It was at the top of my stack feed since a new user posted an answer to it and i was reviewing his post. – John Lord Dec 13 '19 at 20:26
21

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}

Tom Jonckheere
  • 1,630
  • 3
  • 20
  • 37
  • 1
    Just remember that the "name" property for your new route has to be unique. "DefaultApi" is usually already defined. – ComeIn Apr 27 '16 at 15:45
13

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.

Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
4

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)
Andrew
  • 8,322
  • 2
  • 47
  • 70
3

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.

Rune
  • 8,340
  • 3
  • 34
  • 47
2

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

This might be useful for someone who has everything done right still facing issue. For them "above error may also cause due to ambiguous reference".

If your Controller contains

using System.Web.Mvc;

and also

using System.Web.Http;

It will create ambiguity and by default it will use MVC RouteConfig settings instead of WebApiConfig settings for routing. Make sure for WebAPI call you need System.Web.Http reference only

Vijay Kumbhoje
  • 1,401
  • 2
  • 25
  • 44
1

I was facing the Same Error.

Solution: The name of the variable in the View through which we are passing value to Controller should Match the Name of Variable on Controller Side.

.csHtml (View) :

@Html.ActionLink("Edit", "Edit" , new { id=item.EmployeeId })

.cs (Controller Method):

 [HttpGet]
            public ActionResult Edit(int id)
            {
                EmployeeContext employeeContext = new EmployeeContext();
                Employee employee = employeeContext.Employees.Where(emp => emp.EmployeeId == id).First();
                return View(employee);
            }
Paramjot Singh
  • 627
  • 4
  • 8
1

Make the id parameter be a nullable int:

public ActionResult Edit(int? id, User collection)

And then add the validation:

if (Id == null) ...
John Lord
  • 1,941
  • 12
  • 27
  • not sure if the null check is necessary in the code block. I'm 99% sure it will pass to the DB with a zero index to signify it's a new record. – John Lord Dec 11 '19 at 21:48
0

Just in case this helps anyone else; this error can occur in Visual Studio if you have a View as the open tab, and that tab depends on a parameter.

Close the current view and start your application and the app will start 'Normally'; if you have a view open, Visual Studio interprets this as you want to run the current view.

0

Just change your line of code to

<a href="~/Required/Edit?id=@item.id">Edit</a>

from where you are calling this function that will pass corect id

Aneeq Azam Khan
  • 992
  • 1
  • 10
  • 23
0

I had the same error, but for me, the issue was that I was doing the request with a wrong GUID. I missed the last 2 characters.

360476f3-a4c8-4e1c-96d7-3c451c6c86
360476f3-a4c8-4e1c-96d7-3c451c6c865e
Alin Ciocan
  • 3,082
  • 4
  • 34
  • 47
0

Just add Attribute routing if it is not present in appconfig or webconfig

config.MapHttpAttributeRoutes()
anirudh talluri
  • 81
  • 1
  • 2
  • 12
0

If you're confused why your id is passing a null value via your razor file, I had the order of the overload wrong. You don't have to worry about it being nullable in this case.

Example:

This will NOT pass your id, since the overload is not in the correct position:

@Html.ActionLink("Edit", "Edit", "Controller", new { @class = "btn btn-primary" }, new { @id = x.Id })

This is the correct order to pass id, with html attributes after:

@Html.ActionLink("Edit", "Edit", "Controller", new { @id = x.Id }, new { @class = "btn btn-primary" })
pkucas
  • 158
  • 6
0

@Html.ActionLink(item.Name, "Edit", new { id = item.Id }) here notice that parameters given to the ActionLink() is in order.

  1. first parameter is for the text field to show on-page.
  2. second one is for action URL.
  3. List one is for ID reference.
0

I had the same error, but for me, the issue was that

I need to add in Index view the following missing in details action link

new { id = item.user_id}

This is the complete code :

    @foreach (var item in Model)
 {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.user_id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.user_name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.user_password)
            </td>
    
            @Html.ActionLink("Details", "Details", new { id = item.user_id}) 
               
        </tr>
    }
Abdullah
  • 983
  • 12
  • 26
0

If the URL of your GET request is definitely correct - ensure you are not sending anything in the request body.

It was causing this error for me when sending it from Postman.

Zar Shardan
  • 5,675
  • 2
  • 39
  • 37