简体   繁体   English

形成MVC /控制器/动作链接的最佳实践

[英]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: 我一直在研究的部分代码是指定一个URL:

<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? 1)在这种情况下,为内部行为形成网址的最佳做法是什么? Both work, just wondering what is better. 两者都有效,只是想知道什么是更好的。

2) Is there a benefit to using one versus the other? 2)使用一个与另一个有利吗?

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: 我更喜欢使用ActionLinks:

@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. @hutchonoid有点触及这一点,但虚拟路径只是好处的一部分。 While the default route pattern is controller/action/id? 虽然默认路由模式是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. 特别是如果你在MVC5 +中使用属性路由,URL实际上可以是任何东西 ,甚至可能不包括控制器或动作名称。

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. 通过使用Url.ActionHtml.ActionLink处理所有链接,您可以抽象视图对URL的了解,这是一件非常好的事情。 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. 真正的关注点分离是MVC的基础,它要求件尽可能“愚蠢”,只要知道或关心它所需要的东西。

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. 如果您最终使用属性路由,我会更进一步,实际建议命名所有路由,然后使用Url.RouteUrl / Html.RouteLink而不是以动作为中心的版本。 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. 您也可以通过标准路由在技术上执行此操作,但使用标准路由命名路由将要求您手动定义每个路由,而不是依赖于默认路由或一组默认路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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