0
votes

I need to create a custom route with MVC to build a custom search:

Default Home's Index's Action:

    public virtual ActionResult Index()
    {
        return View();
    }

And I would like to read a string like this:

    public virtual ActionResult Index(string name)
    {

        // call a service with the string name

        return View();
    }

For an URL like:

www.company.com/name

The problem is that I have this two routes but it's not working:

        routes.MapRoute(
            name: "Name",
            url: "{name}",
            defaults: new { controller = "Home", action = "Index", name = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", area = "", id = UrlParameter.Optional }
        );

This way, any controller other then Home is redirected to Home, and if I switch the order, it can't find the Index Home Action.

1

1 Answers

0
votes

You can use attribute routing for this. You can see the details about the package here. After installing the attribute routing package. Now a days it is installed by default for MVC5 application. Change your action method as below:

[GET("{name}")]
public virtual ActionResult Index(string name)
{

    // call a service with the string name

    return View();
}

Here's a catch for the code above: The router will send the requests without the name also to this action method. To avoid that, you can change it as below:

[GET("{name}")]
public virtual ActionResult Index2(string name)
{

    // call a service with the string name

    return View("Index");
}