ASP.NET - ActionResult parameter is coming back null always when passing string - why?
In you Global.asax.cs
file, you will have the following route mapped by default:
routes.mapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
That means that an url like http://localhost:2345/Bank/EmployeeDetails/3d34xyz
will go to the Bank
controller, the EmployeeDetails
action and pass the value 3d34xyz
into a parameter named id
. It is perfectly alright to pass a string, but in order to make it work you have two options:
1) Rename the variable to id
in your action method.
public ActionResult EmployeeDetails(string id) { ... }
2) Add another route that matches whatever name you want for your string. Make sure to make it more specific than the default route, and to place it before the default route in the Global.asax.cs
file.
routes.mapRoute(
"BankEmployeeDetails"
"Bank/EmployeeDetails/{myString}"
new { controller = "Bank", action = "EmployeeDetails", myString = UrlParameter.Optional });
This will pass a default value of null
to myString
if no value is passed in the url, but with the url you specified you will pass the value 3d34xyz
.
Rename myString
to id
if you are using the default route table.
Assuming you haven't modified the default routes (In your Global.asax.cs):
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
The method is expecting it to be named "id".