0

我的 webapp 中有一些链接,如下所示:

localhost:12345/?something=1
localhost:12345/?something=2
localhost:12345/?something=3
localhost:12345/?something=4

最后的每个数字都是一个 ID,我需要将其传递给我的控制器以显示与其相关的信息。

我知道我需要routes.MapRoute在我的页面中创建一个新global.asax页面,但我不太确定如何去做。我试过这个:

routes.MapRoute(
    "Id", // Route name
    "{controller}/{action}/{*Id}", // URL with parameters
    new { controller = "Home", action = "Id", Id = "" } // Parameter defaults
);

- -编辑 - -

我只有通过执行以下操作才能成功让每个人都喜欢展示:

routes.MapRoute(
    "IdRoute", // Route name
    "{Id}", // URL with parameters
    new { controller = "Home", action = "Index", id = 1 } // Parameter defaults
);

这确实有效,但是,这只适用于一个 id(特别是 1)。我不太确定该怎么做,但我需要我需要:

localhost:12345/?something=1

显示 id 1 的信息,

localhost:12345/?something=2

显示 id 2 的信息,

localhost:12345/?something=3

显示 id 3 的信息。

我将有数百个 id,所以硬编码不是一个方便的选择。到目前为止,我没有运气。任何帮助将非常感激!谢谢!

4

2 回答 2

0

如果您在 HomeController 中有以下操作:

public ActionResult SomeAction(int Id)
    {
        return View()
    }

您可以使用以下任一路线:

//* For Id = 3 this will return path "Home/SomeAction/3" 
routes.MapRoute(
                name: "First",
                url: "{controller}/{action}/{Id}",
                defaults: new { controller = "Home", action = "SomeAction", Id= UrlParameter.Optional}
            );


//* For Id = 3 this will return path "SomeAction/3" 
routes.MapRoute(
                name: "First",
                url: "{action}/{Id}",
                defaults: new { controller = "Home", action = "SomeAction", Id= UrlParameter.Optional}
            );

//* For Id = 3 this will return path "Home/SomeAction(3)" 
routes.MapRoute(
                name: "First",
                url: "{controller}/{action}({Id})",
                defaults: new { controller = "Home", action = "SomeAction", Id= UrlParameter.Optional}
            );


//* For Id = 3 this will return path "LadyGaga/SomeAction/3" 
routes.MapRoute(
                name: "First",
                url: "LadyGaga/{action}/{Id}",
                defaults: new { controller = "Home", action = "SomeAction", Id= UrlParameter.Optional}
            );
于 2013-08-08T20:43:57.887 回答
0
        routes.MapRouteWithName(
            "RootName",
            "{id}",
            new { controller = "Home", action = "Index", id = 1 });

这将产生像这样的链接 localhost/1 如果你想要这种链接 localhost/?id= 1 那么:

        routes.MapRouteWithName(
            "RootName",
            String.Empty,
            new { controller = "Home", action = "Index"});


public ActionResult Index(int id)
    {
        //do something with id, make query to database whatever

        // u usually have model class so you would fill model with your data
        var model = new YourModel();
        //...
        return View("Index", model);
    }
于 2013-08-05T13:49:38.373 回答