Reputation: 11
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
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:
Upvotes: 0