I want to get the parameter from a url as below:
www.domain.com/Controller/Action/Parameter
In my controller:
public ActionResult Action()
{
//some codes
}
User enters url as above and should navigate the the specific controller. How do I get the 'Parameter' in the Action of my controller?
3 Answers 3
You need 2 things: 1) add parameter to your action, ie: Action(string param, ...)
2) configure the routing to tell mvc how to map route data to parameters. Default mvc route is configured to map /## to "id" parameter, but you can add more routes to map other parameters as you need. For example add this line to your App_Start/RouteConfig.cs file:
routes.MapRoute(
name: "CustomRoute",
url: "{controller}/{action}/{param}
);
note that "{param}" match the name of your action parameter.
Comments
Example
public ActionResult Action()
{
string param1 = this.Request.QueryString["param"];
}
Comments
When someone enter url like the example above, you can do this to get the segment value in your controller.
URL: www.domain.com/Controller/Action/Parameter
Controller:
public ActionResult Action()
{
string parameter = this.Request.Url.Segments[segmentIndex];
//The segmentIndex in the url above should be 3
}
Comments
Explore related questions
See similar questions with these tags.
public ActionResult Action(string id)assuming your using the default route (in your example, the value ofidwill be"Parameter")