请有人向我解释一下,ActionLink(通常是 Html 助手)从哪里获得正确的路线,以及它如何创建正确的路径。例如:
对于这样的路由
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
操作链接看起来像:
@Html.ActionLink("MyCoolLink","About","Home")
生成的 HTML 看起来像:
<a href="/Home/About">About</a>
如何为同一路由定义自定义 href
路径,假设一个看起来像这样的路径:
href="/About"
or
href="Home.myDomain.com/About"
谢谢!
最佳答案
Url.Content
:在内部, VirtualPathUtility
在使用 Url.Content
时使用.
并且,Html.ActionLink
(以及 Url.RouteUrl
),使用 RouteCollection.GetVirtualPath
方法。 ActionLink
实际上特定于 MVC( Action 和 Controller 参数)和 Url.RouteUrl
更通用。
Microsoft 构建了 ActionLink
方法确实作为扩展方法。如果这些扩展仍然不能满足您的目的,我们鼓励您编写自己的扩展。
从 here
下载源代码了解 Microsoft 如何实现这些扩展。
此外,让我们以创建自定义 HtmlHelper
的示例结束。方法。
创建自定义 HtmlHelper
时,下面的 namespace /类很适合阅读方法。
System.Web.Mvc.Html Namespace
System.Web.Mvc.TagBuilder Class
System.Web.Mvc.ModelMetaData Class
System.Web.Mvc.ExpressionHelper Class
System.Linq.Expressions.Expression<TDelegate> Class
以下示例展示了如何创建/添加自定义 <span>
HTML.ActionLink
中的标签
<a href="[action-link]"><span>[action-link text]</span></a>
为了开始这个,创建一个名为 HtmlExtensions
的静态类.让我们创建一个名为 ActionLinkWithSpan
的扩展方法这将扩展 HtmlHelper
类(class)。
namespace Tutorial.Examples
{
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
public static class HtmlExtensions
{
public static MvcHtmlString ActionLinkWithSpan(this HtmlHelper html,
string linkText,
string actionName,
string controllerName,
object htmlAttributes)
{
RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
TagBuilder linkTag = new TagBuilder("a");
TagBuilder spanTag = new TagBuilder("span");
spanTag.SetInnerText(linkText);
// Merge Attributes on the Tag you wish the htmlAttributes to be rendered on.
// e.g. linkTag.MergeAttributes(attributes);
spanTag.MergeAttributes(attributes);
UrlHelper url = new UrlHelper(html.ViewContext.RequestContext);
linkTag.Attributes.Add("href", url.Action(actionName, controllerName));
linkTag.InnerHtml = spanTag.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(linkTag.ToString(TagRenderMode.Normal));
}
}
}
This link 建议深入了解创建自定义 MVC 方法。
关于c# - ActionLink、Html.BeginForm、Url.Content如何匹配正确的Route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18944004/