从控制器内部使用 Html.ActionLink 和 Url.Action(...)
我想编写一个 HtmlHelper 来呈现具有预设值的 ActionLink,例如。
<%=Html.PageLink("Page 1", "page-slug");%>
其中PageLink
是一个使用已知的Action和Controller调用ActionLink
的函数,例如。 “索引”和“页面”。
由于 HtmlHelper
和 UrlHelper
不存在于 Controller
或类中,因此如何从类内部获取操作的相对 URL?
更新:鉴于我现在已经积累了三年的经验,这是我的建议:只需使用 Html.ActionLink("My Link", new {controller = "Page", slug = " page-slug" })
或者更好,
<a href="@Url.Action("ViewPage",
new {
controller = "Page",
slug = "my-page-slug" })">My Link</a>
您的扩展方法可能很可爱且简短,但它增加了另一个未经测试的故障点和新的员工学习要求,而没有增加任何实际价值。将其视为设计一个复杂的系统。为什么要添加另一个移动部件,除非它增加了可靠性(没有)、可读性(很少,一旦你阅读了更多文档)、速度(没有)或并发性(没有)。
I want to write an HtmlHelper to render an ActionLink with pre-set values, eg.
<%=Html.PageLink("Page 1", "page-slug");%>
where PageLink
is a function that calls ActionLink
with a known Action and Controller, eg. "Index" and "Page".
Since HtmlHelper
and UrlHelper
do not exist inside a Controller
or class, how do I get the relative URL to an action from inside a class?
Update: Given the additional three years of accrued experience I have now, here's my advice: just use Html.ActionLink("My Link", new { controller = "Page", slug = "page-slug" })
or better yet,
<a href="@Url.Action("ViewPage",
new {
controller = "Page",
slug = "my-page-slug" })">My Link</a>
Your extension method may be cute and short, but it adds another untested point-of-failure and a new learning requirement for hires without adding any real value whatsoever. Think of it as designing a complex system. Why add another moving part, unless it adds reliability (no), readability (little, once you read more docs), speed (none) or concurrency (none).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定我是否真的清楚地理解了你的问题,但是,让我尝试一下。
要创建像您所描述的 HtmlHelper 扩展,请尝试以下操作:
至于从类获取 URL 的问题,取决于您将实现它的类的类型。例如,如果您想从 HtmlHelper 扩展获取当前控制器和操作,您可以使用:
如果您想从控制器获取它,您可以使用基类 (Controller) 中的属性/方法来构建 URL。例如:
Not sure I actually understood your question clearly, but, let me try.
To create a HtmlHelper extension like you described, try something like:
As for your question on getting a URL from a class, depends on what kind of class you'll implement it. For example, if you want to get the current controller and action from a HtmlHelper extension, you can use:
If you want to get it from a controller, you can use properties/methods from the base class (Controller) to build the URL. For example: