Amazing User
Amazing User

Reputation: 3563

NULL value for "System.Int32"

I read book "ASP.NET MVC5" by Freeman and I try to add administration page to my site. Now when I go to the page http://localhost:63843/Admin/Edit, I have error:

Dictionary of the parameters contains an entry with a NULL value for the parameter "productId" type "System.Int32", not allowing the value NULL, the method for "System.Web.Mvc.ViewResult Edit (Int32)" in "SportsStore.WebUI.Controllers.AdminController". An optional parameter must be a reference type, type, allowing the value NULL, or it must be declared as an option. Parameter name: parameters

public class AdminController : Controller
{
    private IProductRepository repository;

    public AdminController(IProductRepository repo) {
        repository = repo;
    }

    public ViewResult Edit(int productId) {
        Product product = repository.Products
            .FirstOrDefault(p => p.ProductID == productId);
        return View(product);
    }
}

But here is all references to Edit and there is no any NULL value:

Product p1 = target.Edit(1).ViewData.Model as Product;
Product p2 = target.Edit(2).ViewData.Model as Product;
Product p3 = target.Edit(3).ViewData.Model as Product;
Product result = (Product)target.Edit(4).ViewData.Model;

When I comment it, nothing changes. I can't uderstand, where is NULL value.

Upvotes: 0

Views: 1399

Answers (4)

black.rook
black.rook

Reputation: 41

In your line

public ViewResult Edit(int productId) {

you have the parameter productId defined as int. The message tells no more than this must be a nullable parameter or an optional one. So just chage it either to

// nullable
public ViewResult Edit(int? productId) { ... }

or

// optional
public ViewResult Edit(int productId = -1) { ... }

so any call of Edit will accept an incoming null - regardless if this will happen or not.


What about make the parameter be an int? ans Set a breakpoint inside the function to analyse the stacktrace/ callhirarchy to find out who tried the null-call ..?

Upvotes: 1

Uriil
Uriil

Reputation: 12618

The problem is in method declaration:

public ViewResult Edit(int productId)

You expecting productId, but not passing it: http://localhost:63843/Admin/Edit. URL should be: http://localhost:63843/Admin/Edit/1

Upvotes: 2

Mark Cidade
Mark Cidade

Reputation: 99957

The null value comes from when you visit http://localhost:63843/Admin/Edit without specifying the productId, as in http://localhost:63843/Admin/Edit?productId=1.

You can make the productId optional by making it nullable:

public ViewResult Edit(int? productId) 
{
   ...
}

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

Your action needs a parameter which is int and you are not passing it.if you put in browser /Edit?ProductId=1` it will work, or make action parameter null able.

public ViewResult Edit(int? ProductId)

now it will not throw error.

Upvotes: 2

Related Questions