ASP.NET MVC routing

我怕爱的太早我们不能终老 提交于 2019-12-23 15:40:34

问题


Up until now I've been able to get away with using the default routing that came with ASP.NET MVC. Unfortunately, now that I'm branching out into more complex routes, I'm struggling to wrap my head around how to get this to work.

A simple example I'm trying to get is to have the path /User/{UserID}/Items to map to the User controller's Items function. Can anyone tell me what I'm doing wrong with my routing here?

routes.MapRoute("UserItems", "User/{UserID}/Items", 
                      new {controller = "User", action = "Items"});

And on my aspx page

Html.ActionLink("Items", "UserItems", new { UserID = 1 })

回答1:


Going by the MVC Preview 4 code I have in front of me the overload for Html.ActionLink() you are using is this one:

public string ActionLink(string linkText, string actionName, object values);

Note how the second parameter is the actionName not the routeName.

As such, try:

Html.ActionLink("Items", "Items", new { UserID = 1 })

Alternatively, try:

<a href="<%=Url.RouteUrl("UserItems", new { UserId = 1 })%>">Items</a>



回答2:


Can you post more information? What URL is the aspx page generating in the link? It could be because of the order of your routes definition. I think you need your route to be declared before the default route.




回答3:


Firstly start with looking at what URL it generates and checking it with Phil Haack's route debug library. It will clear lots of things up.

If you're having a bunch of routes you might want to consider naming your routes and using named routing. It will make your intent more clear when you re-visit your code and it can potentially improve parsing speed.

Furthermore (and this is purely a personal opinion) I like to generate my links somewhere at the start of the page in strings and then put those strings in my HTML. It's a tiny overhead but makes the code much more readable in my opinion. Furthermore if you have or repeated links, you have to generate them only once.

I prefer to put

<% string action = Url.RouteUrl("NamedRoute", new 
    { controller="User",
      action="Items",
      UserID=1});%>

and later on write

<a href="<%=action%>">link</a>



回答4:


Html.ActionLink("Items", "User", new { UserID = 1 })


来源:https://stackoverflow.com/questions/118851/asp-net-mvc-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!