我的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
);
--- --- EDIT
我只是通过以下方式成功让每个人都喜欢显示:
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,因此编写某些内容并不是一个方便的选择。到目前为止我没有运气。任何帮助将非常感激!谢谢!
答案 0 :(得分: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);
}
答案 1 :(得分:0)
如果你有以下Action,比如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}
);