I have the following Html:
<%: Html.ActionLink(item.ProductName, "Details", "Product", new { item.ProductId }, null)%>
This is being rendered as:
<a href="/Product/Details?ProductId=1">My Product Name</a>
However, when I click on this, I get the following error:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MyProject.Controllers.ProductController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
It appears that my routing doesn't like the "?ProductId=1" query string.
If I use instead:
<%: Html.ActionLink(item.ProductName, string.Format("Details/{0}", item.ProductId), "Product", null, null)%>
I get the following link rendered:
<a href="/Product/Details/1">My Product Name</a>
...and this works correctly when clicked.
Am I missing something basic here? I'd like to use RouteValues, but I don't understand why this error is being thrown. How can I get my Controller method to accept query string parameters?
The only route mapping I have is:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Change the action parameter to be int ProductId.
public ActionResult Details(int productId)
{
return View("");
}
your controller have to get an "id" parameter because you declared it as not nullable int so when you send productId it still doesn't match the function signature.
when you don't specify the parameter name, the routing defaults in the global.asax change the parameter name to id:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
see the last line.
You are setting the /
character as separators between the controller, the action and the id (the parameters) if you call a url like /Product/Details?ProductId=1
you are calling the controller Product
but the action with the text Details?ProductId=1
and then routing hasn't get the next /
.
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