IT

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

lottoking 2020. 6. 1. 08:09
반응형

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


두 가지 질문이 있습니다.

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

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

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

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

    스팬 텍스트

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


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>

사용자 지정 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();
}

다음은 링크를 수동으로 만들 때 (태그를 사용하여) 아약스 또는 일부 기능을 사용해야하는 경우에 대한 (낮고 더러운) 해결 방법입니다.

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

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


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

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

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

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


나는 사용자 정의 확장 방법으로 끝났다. 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>

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

<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 출력은 깨끗하게 유지됩니다


Here is an uber expansion of @tvanfosson's answer. I was inspired by it and decide to make it more generic.

    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);
        }
    }

It's very simple.

If you want to have something like a glyphicon icon and then "Wish List",

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

My solution using bootstrap components:

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

Please try below Code that may help you.

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

참고URL : https://stackoverflow.com/questions/1974980/putting-html-inside-html-actionlink-plus-no-link-text

반응형