在 ASP.net MVC Razor 中渲染包含 span 的 link?
Render link containing span in ASP.net MVC Razor?
渲染一个简单的 link 很容易:
@Html.ActionLink("About this Website", "About")
但是你会如何用剃须刀语法编写以下内容:
<a>
<span>Hello, I'm inconvenient!</span>
</a>
欣赏正确方向的任何一点:)
我不确定我是否正确地遵循了您的示例,因为它不包含 link 并且 link 的文本与 span 的文本不同,但类似这样的内容应该给出你一个大概的想法:
<a href='@Url.Action("About")'>
<span>Hello, I'm inconvenient!</span>
</a>
使用 Url.Action()
将 return 实际的 hyperlink 而不是元素。
您可以创建一个 custom Html Helper,并可以在应用程序的任何视图中重复使用它:
namespace MyApplication.Helpers
{
public static class CustomHtmlHelepers
{
public static IHtmlString ActionLinkWithSpan(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var span = new TagBuilder("span") { InnerHtml = linkText };
var anchor = new TagBuilder("a") { InnerHtml = span.ToString() };
anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return MvcHtmlString.Create(anchor.ToString());
}
}
}
并在视图中使用它:
@using MyApplication.Helpers;
@Html.ActionLinkWithSpan("LinkText","ActionName","ControllerName",null,null)
输出HTML:
<a href="/ControllerName/ActionName">
<span>LinkText</span>
</a>
渲染一个简单的 link 很容易:
@Html.ActionLink("About this Website", "About")
但是你会如何用剃须刀语法编写以下内容:
<a>
<span>Hello, I'm inconvenient!</span>
</a>
欣赏正确方向的任何一点:)
我不确定我是否正确地遵循了您的示例,因为它不包含 link 并且 link 的文本与 span 的文本不同,但类似这样的内容应该给出你一个大概的想法:
<a href='@Url.Action("About")'>
<span>Hello, I'm inconvenient!</span>
</a>
使用 Url.Action()
将 return 实际的 hyperlink 而不是元素。
您可以创建一个 custom Html Helper,并可以在应用程序的任何视图中重复使用它:
namespace MyApplication.Helpers
{
public static class CustomHtmlHelepers
{
public static IHtmlString ActionLinkWithSpan(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var span = new TagBuilder("span") { InnerHtml = linkText };
var anchor = new TagBuilder("a") { InnerHtml = span.ToString() };
anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return MvcHtmlString.Create(anchor.ToString());
}
}
}
并在视图中使用它:
@using MyApplication.Helpers;
@Html.ActionLinkWithSpan("LinkText","ActionName","ControllerName",null,null)
输出HTML:
<a href="/ControllerName/ActionName">
<span>LinkText</span>
</a>