从内控制器使用Html.ActionLink和Url.Action(...) [英] Using Html.ActionLink and Url.Action(...) from inside Controller
问题描述
我想写的HtmlHelper渲染与pre-设定值的ActionLink的,例如:
I want to write an HtmlHelper to render an ActionLink with pre-set values, eg.
<%=Html.PageLink("Page 1", "page-slug");%>
其中, PageLink
是调用 ActionLink的
与已知的动作和控制器,如函数。 索引和页。
where PageLink
is a function that calls ActionLink
with a known Action and Controller, eg. "Index" and "Page".
由于的HtmlHelper
和 UrlHelper
不要在控制器$ C $存在C>或类,我怎么从类中获取相对URL的动作?
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?
更新:由于额外的三年累积经验我现在有,这是我的建议是:只要使用 Html.ActionLink(我的连接,新{控制器=页,蛞蝓=页面弹头})
或更好,但
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).
推荐答案
不知道其实我明白你的问题清楚了,但是,让我试试。
Not sure I actually understood your question clearly, but, let me try.
要像你描述的创建一个扩展的HtmlHelper,尝试这样的:
To create a HtmlHelper extension like you described, try something like:
using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Something {
public static class PageLinkHelper
{
public static string PageLink(
this HtmlHelper helper,
string linkText, string actionName,
string controllerName, object routeValues,
object htmlAttributes)
{
return helper.ActionLink(
linkText, actionName, controllerName,
routeValues, htmlAttributes);
}
}
}
对于从一个类获得一个网址你的问题,要看是什么样的类,你会实现它。例如,如果你想从一个扩展的HtmlHelper电流控制器和行动,你可以使用:
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:
string currentControllerName = (string)helper.ViewContext
.RouteData.Values["controller"];
string currentActionName = (string)helper.ViewContext
.RouteData.Values["action"];
如果您想从控制器得到它,你可以使用属性/从基类(控制器)的方法来构建URL。例如:
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:
var url = new UrlHelper(this.ControllerContext.RequestContext);
url.Action(an_action_name, route_values);
这篇关于从内控制器使用Html.ActionLink和Url.Action(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!