HTML을 Html.ActionLink () 안에 넣고 링크 텍스트 없음?


169

두 가지 질문이 있습니다.

  1. Html.ActionLink()MVC보기에서 사용할 때 링크 텍스트를 표시하지 않는 방법이 궁금합니다 (실제로 이것은입니다 Site.Master).

링크 텍스트를 허용하지 않는 오버로드 된 버전이 없으며 blank 만 전달하려고 string하면 컴파일러는 비어 있지 않은 문자열이 필요하다고 알려줍니다.

이 문제를 어떻게 해결할 수 있습니까?

  1. <span>앵커 태그 내에 태그 를 넣어야 하지만 작동하지 않습니다 Html.ActionLink();. 다음과 같은 결과를보고 싶습니다.

    스팬 텍스트

ASP.NET MVC의 앵커 태그 안에 태그를 넣을 수 있습니까?


빈 작업 링크의 목적 / 사용은 무엇입니까?
— David

1
탐색 막대에 이미지 스프라이트를 사용하고 <li>있으며 특정 탐색 버튼 (CSS 스타일 시트에 지정된 크기, 배경 위치 등)이 있습니다. 그러나 그것은 무언가에 연결되어야하므로 텍스트를 표시하고 싶지 않습니다. 스프라이트가 나를 위해 그렇게하기를 원합니다.
— MegaMatt

답변:


322

Html.ActionLink를 사용하는 대신 Url.Action을 통해 URL을 렌더링 할 수 있습니다.

<a href="<%= Url.Action("Index", "Home") %>"><span>Text</span></a>
<a href="@Url.Action("Index", "Home")"><span>Text</span></a>

그리고 빈 URL을 수행하려면

<a href="<%= Url.Action("Index", "Home") %>"></a>
<a href="@Url.Action("Index", "Home")"></a>

3
<a href="@Url.Action("Index", "Home")"> <span> Text </ span> </a>을 사용해야했는데 내 개발자가 왜해야하는지 묻지 않았습니다. 이것은 위의 답변을 사용하여 작동하지 않는 것을 찾는 사람에게 도움이 될 수 있습니다.
— Dave Haigh

2
@ Url.Action은 면도기 템플릿을 사용할 때입니다. 두 가지를 모두 볼 수 있도록 답변을 업데이트했습니다.
— David

<a href=@Url.Action("Create", "Product")><span>Create</span></a>작동합니다. 따옴표는 필요하지 않습니다.
— David

1
정적 콘텐츠의 경우 html을 직접 입력하지 않으시겠습니까? 덜 장황하고 단순 해 보입니다
— SkeetJon

Ajax를 사용하려는 경우 Asp.Net Core 2에서 더 이상 실제 옵션이 아닙니다.
— Zorkind

17

사용자 지정 HtmlHelper 확장은 또 다른 옵션입니다. 참고 : ParameterDictionary는 내 유형입니다. RouteValueDictionary를 대체 할 수 있지만 다르게 구성해야합니다.

public static string ActionLinkSpan( this HtmlHelper helper, string linkText, string actionName, string controllerName, object htmlAttributes )
{
    TagBuilder spanBuilder = new TagBuilder( "span" );
    spanBuilder.InnerHtml = linkText;

    return BuildNestedAnchor( spanBuilder.ToString(), string.Format( "/{0}/{1}", controllerName, actionName ), htmlAttributes );
}

private static string BuildNestedAnchor( string innerHtml, string url, object htmlAttributes )
{
    TagBuilder anchorBuilder = new TagBuilder( "a" );
    anchorBuilder.Attributes.Add( "href", url );
    anchorBuilder.MergeAttributes( new ParameterDictionary( htmlAttributes ) );
    anchorBuilder.InnerHtml = innerHtml;

    return anchorBuilder.ToString();
}

14

아약스 또는 수동으로 링크를 만들 때 사용할 수없는 기능 (태그 사용)을 사용해야하는 경우 (낮고 더러운) 해결 방법이 있습니다.

<%= Html.ActionLink("LinkTextToken", "ActionName", "ControllerName").ToHtmlString().Replace("LinkTextToken", "Refresh <span class='large sprite refresh'></span>")%>

'LinkTextToken'대신 텍스트를 사용할 수 있습니다. 교체해야 할 곳이며 actionlink 내부의 다른 곳에서는 발생하지 않는 것이 중요합니다.


6
+1 좋은 생각입니다. 면도기, 당신의 그 모든 랩을해야합니다Html.Raw()
— 캐리 켄달

감사합니다 :) 이제 우리가 사용한 것을 보았으므로 거의 당황 스럽습니다. 서버에서 이러한 일을하는 것은 서버 리소스 낭비입니다 ...
— Goran Obradovic

1
@ Ajax.ActionLink를 사용하고 있으며 모든 date-속성을 수동으로 설정하는 느낌이 들지 않기 때문에 이것이 최선의 해결책입니다. +1
— asontu

감사합니다 .Ajax.ActionLink도 사용할 때 매력처럼 작동했습니다. 속도가 느려지지 않는 것처럼 보였고 동일한 레이아웃과 스타일을 유지해야했습니다.
— Blacky Wolf

그냥 말하기를, 이것은 .Net Core에서 작동하지 않습니다. ToHtmlString ()은 v1에 대해 확실하지 않습니다. v1
— Zorkind

12

Url.Action대신에 사용하십시오 Html.ActionLink:

<li id="home_nav"><a href="<%= Url.Action("ActionName") %>"><span>Span text</span></a></li>

@CraigStunz 왜 Html.ActionLink 대신 Url.Action을 사용해야합니까?
— Roxy'Pro

6

이것은 항상 나를 위해 잘 작동했습니다. 지저분하지 않고 매우 깨끗합니다.

<a href="@Url.Action("Index", "Home")"><span>Text</span></a>


Url.Action에는 htmlAttributes를 사용하는 생성자가 없습니다. ActionLink와 동일하지 않습니다.
— barrypicker

2

나는 사용자 정의 확장 방법으로 끝났다. Anchor 객체 내부에 HTML을 배치하려고 할 때 링크 텍스트는 내부 HTML의 왼쪽 또는 오른쪽에있을 수 있습니다. 이러한 이유로 왼쪽 및 오른쪽 내부 HTML에 매개 변수를 제공하기로 결정했습니다. 링크 텍스트는 중간에 있습니다. 왼쪽 및 오른쪽 내부 HTML은 모두 선택 사항입니다.

확장 메소드 ActionLinkInnerHtml :

    public static MvcHtmlString ActionLinkInnerHtml(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues = null, IDictionary<string, object> htmlAttributes = null, string leftInnerHtml = null, string rightInnerHtml = null)
    {
        // CONSTRUCT THE URL
        var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
        var url = urlHelper.Action(actionName: actionName, controllerName: controllerName, routeValues: routeValues);

        // CREATE AN ANCHOR TAG BUILDER
        var builder = new TagBuilder("a");
        builder.InnerHtml = string.Format("{0}{1}{2}", leftInnerHtml, linkText, rightInnerHtml);
        builder.MergeAttribute(key: "href", value: url);

        // ADD HTML ATTRIBUTES
        builder.MergeAttributes(htmlAttributes, replaceExisting: true);

        // BUILD THE STRING AND RETURN IT
        var mvcHtmlString = MvcHtmlString.Create(builder.ToString());
        return mvcHtmlString;
    }

사용 예 :

다음은 사용법의 예입니다. 이 예제에서는 링크 텍스트의 오른쪽에있는 내부 HTML 만 원했습니다 ...

@Html.ActionLinkInnerHtml(
    linkText: "Hello World"
        , actionName: "SomethingOtherThanIndex"
        , controllerName: "SomethingOtherThanHome"
        , rightInnerHtml: "<span class=\"caret\" />"
        )

결과 :

결과는 다음과 같습니다.

<a href="/SomethingOtherThanHome/SomethingOtherThanIndex">Hello World<span class="caret" /></a>

1

부트 스트랩과 일부 글 리피 콘을 사용할 때 이것이 유용 할 것이라고 생각했습니다.

<a class="btn btn-primary" 
    href="<%: Url.Action("Download File", "Download", 
    new { id = msg.Id, distributorId = msg.DistributorId }) %>">
    Download
    <span class="glyphicon glyphicon-paperclip"></span>
</a>

다운로드 링크를 나타내는 멋진 클립 아이콘이있는 컨트롤러에 대한 링크가있는 A 태그가 표시되며 html 출력은 깨끗하게 유지됩니다


1

@tvanfosson의 답변이 엄청나게 확장되었습니다. 나는 그것에 영감을 받아 그것을 더 일반적인 것으로 결정했습니다.

    public static MvcHtmlString NestedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName,
        string controllerName, object routeValues = null, object htmlAttributes = null,
        RouteValueDictionary childElements = null)
    {
        var htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

        if (childElements != null)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            var anchorTag = new TagBuilder("a");
            anchorTag.MergeAttribute("href",
                routeValues == null
                    ? urlHelper.Action(actionName, controllerName)
                    : urlHelper.Action(actionName, controllerName, routeValues));
            anchorTag.MergeAttributes(htmlAttributesDictionary);
            TagBuilder childTag = null;

            if (childElements != null)
            {
                foreach (var childElement in childElements)
                {
                    childTag = new TagBuilder(childElement.Key.Split('|')[0]);
                    object elementAttributes;
                    childElements.TryGetValue(childElement.Key, out elementAttributes);

                    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(elementAttributes);

                    foreach (var attribute in attributes)
                    {
                        switch (attribute.Key)
                        {
                            case "@class":
                                childTag.AddCssClass(attribute.Value.ToString());
                                break;
                            case "InnerText":
                                childTag.SetInnerText(attribute.Value.ToString());
                                break;
                            default:
                                childTag.MergeAttribute(attribute.Key, attribute.Value.ToString());
                                break;
                        }
                    }
                    childTag.ToString(TagRenderMode.SelfClosing);
                    if (childTag != null) anchorTag.InnerHtml += childTag.ToString();
                }                    
            }
            return MvcHtmlString.Create(anchorTag.ToString(TagRenderMode.Normal));
        }
        else
        {
            return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributesDictionary);
        }
    }

1
당신이 영감을 받아 이것을 할 수있는 능력을 가지고있는 것이 좋습니다. 그러나 중첩 된 foreach 문을보고 실행하고 싶습니다. 대부분의 개발자가 유지 관리 할 수있는 것은 아닙니다. 스톤 블랙 박스 타입 확장 방법으로 꽤 설정되면 가능하지만 코드 냄새가납니다. 꽤 간단한 것에 대해서는 전혀 눈에 띄지 않습니다. 노력해 주셔서 감사합니다.
— Tom Stickel

중첩 된 for 루프에 대해 매우 동의합니다. 간결성을 위해 거기에 있습니다. 최적화 관점에서 그렇습니다. 중첩 된 for 루프는 자체 개인 메소드에 있어야하며 매개 변수를 주장해야하며 코드는 훨씬 더 방어 적이어야합니다.
— william-kid

0

매우 간단합니다.

글리프 콘 아이콘과 같은 것을 원하고 "위시리스트"를 원한다면,

<span class="glyphicon-heart"></span> @Html.ActionLink("Wish List (0)", "Index", "Home")

0

부트 스트랩 구성 요소를 사용하는 솔루션 :

<a class="btn btn-primary" href="@Url.Action("resetpassword", "Account")">
    <span class="glyphicon glyphicon-user"></span> Reset Password
</a>

0

아래 코드가 도움이 될 수 있습니다.

 @Html.ActionLink(" SignIn", "Login", "Account", routeValues: null, htmlAttributes: new {  id = "loginLink" ,**@class="glyphicon glyphicon-log-in"** }) 

그냥 추가, @ 클래스 다음 실제 CSS 클래스는 내 문제를 해결하는 데 도움이
— Ahsanul
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.