I am trying to implement an edit page in order administrator to modify data in database.Unfortunately I am encountering an error.
The code below:
public ViewResult Edit(int productId) {
// Do something here
}
but I am getting this error:
"The parameters dictionary contains a null entry for parameter 'productId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult Edit(Int32)' in 'WebUI.Controllers.AdminController'. To make a parameter optional its type should be either a reference type or a Nullable type.
Parameter name: parameters"
I changed my route in Global.asax.cs
like this:
routes.MapRoute(
"Admin",
"Admin/{action}/{ productId}",
new { controller = "Admin", action = "Edit", productId= "" }
);
but still I am getting the error .
That empty string for productId
(in your default route) will get parsed to a null entry by the Framework, and since int
does not allow null
...you're getting the error.
Change:
public ViewResult Edit(int productId)
to
public ViewResult Edit(int? productId)
if you want to allow for the caller to not have to pass in a product id, which is what it looks like what you want to do based on the way your route is configured.
You could also re-configure your default route to pass in some known default for when no productId is supplied:
routes.MapRoute(
"Admin",
"Admin/{action}/{ productId}",
new { controller = "Admin", action = "Edit", productId= -1 }
I came across the same problem following the worked SportStore example in Pro ASP.Net
The solution was actually that my Index view has the following code.
@Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) |
However my Edit method in my controller was defined as
public ViewResult Edit(int productId)
changing my Index view to read
@Html.ActionLink("Edit", "Edit", new { productId=item.ProductID }) |
fixed the problem
Here is the way how to ignore such argument errors for any controller method invoke:
public class MyControllerBase
{
//...
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
{
var targetSite = filterContext.Exception.TargetSite;
if (targetSite.DeclaringType != null)
if (targetSite.DeclaringType.FullName == typeof(ActionDescriptor).FullName)
if (targetSite.Name == "ExtractParameterFromDictionary") // Note: may be changed in future MVC versions
{
filterContext.ExceptionHandled = true;
filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
return;
}
//...
}
// ...
}
}
productId
should be constrained to int
type.
new {controller="Admin", action="Edit"},
new {productId = @"\d+" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With