Bruno Heringer Bruno Heringer - 7 months ago 35
C# Question

How to create a MVC Route only with a paramter in URL

How to create a route with only a single parameter?

Example: A want to call


My route is:

name: "RouteEvent",
url: "{productName}",
defaults: new { controller = "Product", action = "Details", ProductName= UrlParameter.Optional }

However, this mode does not works and my return is 404.

My View Is:


public ActionResult Index(string productName)
return View();

or (I'am trying also)


public ActionResult Details(string productName)
return View("Details", productName);

Answer Source

I could do it like this.

For resolve this, we have to create a Constraint in specific route. This Constraint must verify the URL's with single paramter to decide which route to use.


public class ProductConstraint : IRouteConstraint
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
           return !Assembly.GetAssembly(typeof(MvcApplication))
                .GetTypes().Where(type => typeof(Controller).IsAssignableFrom(type))
                .Any(c => c.Name.Replace("Controller", "") == values[parameterName].ToString());

And my route like this: (This route must be declared in routeconig.cs first the defaultRoute;

    name: "RouteProduct",
    url: "{ProductName}",
    defaults: new
        controller = "Procuct",
        action = "Detalhe"
    constraints: new { ProductName = new ProductConstraint() }

There may be an error when the ProductName is the same as the Controller. So, think about it maybe do you have to treat this. (A good idea is to handle in Constraint created.

I hope I have helped.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download