0

This is how i designed the RegisterRoutes function. and based on the condition am selecting the Action for HomeController. So far so Good.

string env = "Index";
if (some condition from config)
{
    env = "Test";
}
routes.MapRoute(
    "Default",                                             
    "{controller}/{action}/{id}",                           
    new { controller = "Home", action = env, id = "" }  
);

Problem starts here when am reirecting to other controller by default if dont specify an action(for eg: am calling SampleController) the "env"(Which was set in RegisterRoutes is called. if env is set as "Index" Index action is called, if env is set "Test" Test action is called in all other controllers as well.

My intention is only for HomeController this condition should be set and for all other controller i want Index to be the default action.

How do i make this work ? is it possible to dynamically change the action for all other controllers ? Is there a better way i can do this.

Share your suggestions

Thanks

3
  • 1
    You could make one specific route for "Home/{action}/{id}", new { controller = "Home", action = env } and the default route "{controller}/{action}/{id}", new { controller = "Home", action = "Index" } Commented Feb 24, 2015 at 9:38
  • @StephenMuecke Thanks! I tried but always the default route is getting called ? Commented Feb 24, 2015 at 14:11
  • Did you put "Home/{action}/{id}" first? (the order is important) Commented Feb 25, 2015 at 0:04

1 Answer 1

2

I don't think you should do this in your routing engine. I would route everything in code and call the correct action from in there. For example:

public ActionResult Index()
{
    switch(config) 
    {
        case "OtherAction":
            return OtherAction();

        case "AnotherAction":
            return AnotherAction();

        case "Index":
            break;

        default:
            //Er, how did we get here?
            throw new HttpNotFoundException();
    }

    //Normal index action continues here...

}

public ActionResult OtherAction() { ... }
public ActionResult AnotherAction() { ... }
Sign up to request clarification or add additional context in comments.

Comments

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.