Reputation: 29365
I have a url along the lines of this:
example.com/profile/publicview?profileKey=5
and I want to shorten it to this with routing
example.com/profile/5
How do I do this?
This is my attempt:
routes.MapRoute(
"Profile", "Profile/{profileKey}",
new { controller = "Profile", action = "PublicView", profileKey ="" }
);
But his produces this error:
The parameters dictionary contains a null entry for parameter 'profileKey' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult PublicView(Int32)' in 'Website.Controllers.ProfileController
Action method
public ActionResult PublicView(int profileKey)
{
//stuff
}
Upvotes: 1
Views: 575
Reputation: 807
Try this (untested) code
routes.MapRoute(
"Profile", "Profile/{profileKey}",
new { controller = "Profile", action = "PublicView" }
);
Upvotes: 0
Reputation: 11041
On the controller change the PublicView(int? profileKey)
ANSWER TO COMMENT
Yes, but since your default value in the route is null, you need to handle it. Otherwise, change the default in your route.
MAYBE
This probably won't help, but it is worth a try. Here is the code I have my site:
routes.MapRoute(
"freebies", // Route name
"freebies/{page}", // URL with parameters
new { controller = "Home", action = "Freebies", page = 1 } // Parameter defaults
);
And the link:
http://localhost/freebies/2
And this works fine.
Upvotes: 2
Reputation: 21357
Your route and action method are fine as-is, if and only if, you are always including an integer value in your url as in example.com/profile/5. (I assume this route is defined above the Default route)
What you've defined is a route that defaults profileKey to an empty string if it is not provided in the url, and within your action method you've attempted to bind this value to a non-nullable integer, so if you are attempting example.com/profile or example.com/profile/not-an-int this will throw the exception you are reporting. Your route will assign an empty string to profileKey, but your action method fails to cast this as an integer. As Martin pointed out, one way around this is to use a nullable int instead. An alternative solution would be to default this value in your route to an integer.
If you are still getting the error, make sure the actual URL you are requesting is correct and has the profileKey included. I know sometimes when using the default html and/or url helpers I make a mistake passing in the routeValues and end up rendering a link or posting to a url other than what I was expecting...
Hope that helps
Upvotes: 1
Reputation: 5924
Is that your only route? If not, maybe another route (declared earlier) is matching first, and isn't picking up the profileKey parameter properly.
Upvotes: 0