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

Gra*_*avy 2 asp.net-mvc asp.net-mvc-routing

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

public ActionResult Index(int id = 0)
{

    return view();
}
Run Code Online (Sandbox Code Playgroud)

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

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

http://localhost:8765/ControllerName/?id=4
Run Code Online (Sandbox Code Playgroud)

详情动作......我可以做到这一点.

http://localhost:8765/ControllerName/Details/4
Run Code Online (Sandbox Code Playgroud)

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

http://localhost:8765/ControllerName/4
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

这可能吗?如何让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 }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

更新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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

Gle*_*ven 5

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

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

因此,默认路由/ ControllerName/4正在作为ControllerNameControllerAction 进行交互4,这当然不存在.

如果你添加

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

在它允许的默认值之前

/主页/ 4路由到HomeController行动Indexid=4

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

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

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

  • 您还可以添加路由约束,以便仅在参数为整数时才匹配. (2认同)