Ashkan.H
Ashkan.H

Reputation: 121

How to skip other action names while defining a custom route in mvc 4

I want my visitors be able to redirect to detail page of a business by entering the name of that business. So I have this custom route:

routes.MapRoute(
                "Business", 
                "{name}", 
                new { controller = "Business", action = "Show" },
                new[] { "Sample.Web.UI.Controllers" });

And I have this one as default:

routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                new[] { "Sample.Web.UI.Controllers" });

which is ordered after the custom one. And at last I have an action called show that gets the business by name entered by visitor. Now when every Index Action methods that I have in home page like:

@this.Html.ActionLink("More", "Index", "SomeThing")

Redirects to Sample/SomeThing and calls the action show I mentioned above and returns null. Is there anyway I can handle this?

Upvotes: 0

Views: 459

Answers (1)

Ashkan.H
Ashkan.H

Reputation: 121

I solved the problem by adding this class:

public class NotEqual : IRouteConstraint
    {
        private readonly ICollection<string> match;

        public NotEqual(ICollection<string> match)
        {
            this.match = match;
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var result = new List<bool>();
            this.match.ToList()
                .ForEach(m => 
                    result.Add(string.Compare(values[parameterName].ToString(), m, StringComparison.OrdinalIgnoreCase) != 0 &&
                    !values[parameterName].ToString().Contains("Test")));
            return result.TrueForAll(r => r);
        }
    }

And making my custom route like this:

routes.MapRoute(
                "Business",
                "{name}",
                new { controller = "Business", action = "Show" },
                new { name = new NotEqual(new System.Collections.ObjectModel.Collection<string> { "Foo", "Test" }) },
                new[] { "Sample.Web.UI.Controllers" });

Upvotes: 1

Related Questions