trstill
trstill

Reputation: 11

Is it possible to use a variable for the action in the MVC routeconfig file

I am trying to see if I can use the action part of routes.MapRoute for a route in routeconfig.cs file

I tried:

        routes.MapRoute(
           name: "Person",
           url: "person/{action}/{param1}",
           new { controller = "Person", action ={action], param1 = UrlParameter.Optional }
       );

Trying to use {action} in the new section gives a syntax error when I try to use action = {action}.

How can I use a variable to set the new controller action?

Upvotes: 0

Views: 55

Answers (1)

Dave Barnett
Dave Barnett

Reputation: 2226

If you've specified {action} in the url parameter then that will be used as the action. I think you are getting confused with the defaults parameter. In here you specify defaults so something like {action} is out of place.

I believe this is the code you are looking for

  routes.MapRoute(
                name: "Person",
                url: "person/{action}/{param1}",
                defaults: new { controller = "Person", action ="Index", param1 = UrlParameter.Optional } );

Suppose this is your person controller

using System.Web.Mvc;

namespace ActionVar.Controllers
{
    public class PersonController : Controller
    {
            public ActionResult Index(string param1 = null)
        {
            return Content($"Person controller default action.  Param1 ={param1}");
        }

        public ActionResult Edit(string param1 = null)
        {
            return Content($"Person controller edit action.  Param1 ={param1}");
        }
    }
}

Some urls and how they will be routed for the above controller:

  • /person - in this case no action provided so the default action will be used, i.e. index, and the value of param1 will be null
  • /person/index/myparam1 - The string after person is index so that will be the action and the value of param1 will be myparam1
  • /person/edit/myparam1 - This time the action will be edit and param1 will take the value myparam1

Upvotes: 0

Related Questions