2

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

public ActionResult Index(int id = 0)
{

    return view();
}

我希望将 id 传递给 index 操作,但它的工作方式似乎与 details 操作不同。

例如,如果我想将 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 }
        );
    }
}

当我访问 localhost:1234/Fix/3 时,更新新的 RouteConfig 类仍然不起作用

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

1 回答 1

5

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

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

因此,默认路由 /ControllerName/4 被解释为ControllerNameControllerAction 4,这当然不存在。

如果你添加

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

在它允许的默认值之前

/Home/4被路由到HomeController行动Indexid=4

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

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

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

于 2012-10-07T22:57:06.830 回答