Direct route to custom search with MVC

前提是你 提交于 2019-12-25 07:25:07

问题


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:


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");
}


来源:https://stackoverflow.com/questions/23613811/direct-route-to-custom-search-with-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!