erntay2
erntay2

Reputation: 140

Get parameter from url asp.net mvc 4

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?

Upvotes: 0

Views: 6334

Answers (3)

erntay2
erntay2

Reputation: 140

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 
}

Upvotes: 0

tede24
tede24

Reputation: 2354

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.

Upvotes: 1

prola
prola

Reputation: 2833

Example

public ActionResult Action()
{
    string param1 = this.Request.QueryString["param"];
}

Upvotes: 0

Related Questions