ASP.NET MVC 4路由查询 - 将查询字符串传递给索引操作

时间:2012-10-07 22:52:08

标签: asp.net-mvc asp.net-mvc-routing

我有一个带索引动作的控制器。

public ActionResult Index(int id = 0)
{

    return view();
}

我希望将id传递给索引操作,但它似乎与详细操作的工作方式不同。

e.g。如果我想将id 4传递给索引动作,我必须访问url:

http://localhost:8765/ControllerName/?id=4

详情动作......我可以这样做。

http://localhost:8765/ControllerName/Details/4

我想用Index做什么就像......

http://localhost:8765/ControllerName/4

当我访问此网址时,出现错误:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /fix/1

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

这可能吗?如何让MVC以与详细信息相同的方式自动处理索引操作?

由于

更新 - 我当前的路线配置

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

更新NEW RouteConfig类在我访问localhost时仍然无效:1234 / Fix / 3

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

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

1 个答案:

答案 0 :(得分:5)

更新值得指出的是,/ ControllerName / Index / 4应该与默认路由一起使用。

使用默认路由时,它希望第二个参数是控制器名称。

因此,默认路由/ ControllerName / 4正在作为ControllerNameController动作4进行交互,当然不存在。

如果你添加

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

在默认值之前允许

使用HomeController

/ Home / 4路由到Index操作id=4

我没有测试过,它可能与默认设置冲突。您可能需要在路径中明确指定控制器,即:

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

(显然,用您实际想要路由到的控制器替换Home