3

I have this URL:

/controller/action/value

and this action:

public ActionResult Get(string configName,string addParams)
{
}

How do I set up my routing table to get the routing engine bind the value to the configName parameter for any action in the Config controller?

2
  • With regards to the optional parameters, which version of MVC are you using to do this? Commented Mar 8, 2011 at 13:16
  • 1
    FYI, there is nothing RESTFUL about pretty URLs. Commented Mar 9, 2011 at 13:26

3 Answers 3

4

Well, first off, that is incomplete. You don't have a method name.

Secondly, this will already work with URLs of the format:

/controller/action?configName=foo&addparams=bar

Here's how to do it with pretty routes:

routes.MapRoute(
      "YourMapping",                                            
      "{controller}/{action}/{configName}/{addParams}");

or

routes.MapRoute(
      "YourMapping",                                            
      "{controller}/{configName}/{addParams}",     
      new {
          controller = "YourController",
          action = "YourAction"
      },
      new {
          controller = "YourController"  // Constraint
      });

if you want to exclude the action from the URL.

Sign up to request clarification or add additional context in comments.

1 Comment

Ups, I added the action name. Yes I know but I'd like to have the url like /config/get/value. The second parameter is optional.
3

You could add a new route above the default

routes.MapRoute(
  "Config", 
  "config/{action}/{configName}/{addParams}",
  new { controller = "Config", action = "Index" }
);

routes.MapRoute(
  "Default", // Route name
  "{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Which will allow you to use the route /config/actionName/configName/addParamsValue. Your other routes should be unaffected by this.

Comments

2
routes.MapRoute(
      "ValueMapping",                                            
      "config/{action}/{configName}/{addParams}",          
      new { controller = "Config", action = "Index", configName= UrlParameter.Optional, addParams = UrlParameter.Optional }  // Parameter defaults);

Setting default Controller to Home, with a Default Action of Index

So the Url: /config/get/configNameValue/AddParamValue

would match this Method:

public ActionResult Get(string configName,string addParams)
{
//Do Stuff 
}

1 Comment

I guess this works for the whole application, but I need it only for the Config controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.