简体   繁体   中英

Best practice on forming links to MVC /controller/actions

I was wondering what the best practice was for specifying an action on a certain controller.

Parts of the code I've been working on are specifying a url as:

<a href="/controller/action"/>

I'm generally not a big fan of this style. I've preferred to use:

<a href='@Url.Action("Action", "Controller")'/>

1) What is the best practice in forming urls for internal actions in this case? Both work, just wondering what is better.

2) Is there a benefit to using one versus the other?

Of the two options I would say the second is the better approach as it will work with virtual paths/directories:

<a href='@Url.Action("Action", "Controller")'/>

I prefer to use ActionLinks though:

@Html.ActionLink("text", "action", "controller")

如果你真的想要的话,你也可以创建StronlyTyped ActionLinks

@(Html.ActionLink<CustomersController>(x => x.Index(), "Customers"))

@hutchonoid sort of touched on this, but virtual paths are just one part of the benefit. While the default route pattern is controller/action/id? , it doesn't have to be that way. Especially if you're using attribute routing in MVC5+, the URL could be literally anything , and may not even include the controller or action name.

By handling all your links using Url.Action or Html.ActionLink , you abstract the view's knowledge of the URL, which is a very good thing. True separation of concerns, which is fundamental to MVC, requires pieces to be as "dumb" as possible, only knowing or caring about the things that it needs to.

If you do end up using attribute routing, I would go a step further and actually recommend naming all your routes, and then using Url.RouteUrl / Html.RouteLink instead of the action-centric versions. This provides even greater abstraction, as you could then have a completely different action or even controller handle that named route, without changing any of your views. You could also technically do this with standard routing, but naming routes with standard routing would require you to manually define each route, instead of relying on a default route or set of default routes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM