Steven Yong
Steven Yong

Reputation: 5426

MVC - Avoiding "The parameters dictionary contains a null entry for parameter"

I have a MVC controller:

    public ActionResult EditProduct(int id)
    {
        var model = products.GetById(id);

        return View(model);
    }

    [HttpPost]
    public ActionResult EditProduct(Product product)
    {
        products.Update(product);
        products.Commit();

        return RedirectToAction("ProductList");
    }

and when I do this http://localhost:56339/Admin/EditProduct without passing in the id like this http://localhost:56339/Admin/EditProduct/1, I will get the error The parameters dictionary contains a null entry for parameter.

How do I prevent that if users type that in the URL without the id?

Upvotes: 0

Views: 415

Answers (2)

Sunil Kumar
Sunil Kumar

Reputation: 3242

You can achieve this from two ways :

1) Set Nullable type parameter

public ActionResult EditProduct(int? id)
    {
 if (id == null)
            {
         // nullable logic here   
            }
            else { 
            // your logic here
            }
       return View();
    }

2) Set Optional Parameter

public ActionResult EditProduct(int id=0)
        {
     if (id == 0)
                {
             // nullable logic here   
                }
                else { 
                // your logic here
                }
           return View();
        }

Hope it will helps you.

Upvotes: 2

Steven Yong
Steven Yong

Reputation: 5426

From Stephen Muecke: You could make it nullable - int? id - and the redirect to another error page if it has no value.

Upvotes: 1

Related Questions