简体   繁体   中英

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?

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.

Example

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

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 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM