Reputation: 5426
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
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
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