development

Html.ActionLink가“? Length = 4”로 렌더링되는 이유

big-blog 2020. 3. 15. 09:40
반응형

Html.ActionLink가“? Length = 4”로 렌더링되는 이유


왜이 코드에 대해 매우 혼란 스럽습니다.

Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" })

이 링크의 결과 :

<a hidefocus="hidefocus" href="/Home/About?Length=4">About</a>

hidefocus부분은 내가 달성하려는 목표이지만 어디에서 ?Length=4오는가?


Length = 4는 문자열 객체를 직렬화하려는 시도에서 온 것입니다. 코드에서이 ActionLink방법을 실행 중입니다 .

public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes)

stringrouteValues에 대해 "홈"오브젝트를 가져옵니다. MVC 배관은 공용 특성을 검색하여이를 루트 값으로 변환합니다. string객체 의 경우 유일한 공용 속성은 Length이며 길이 매개 변수로 정의 된 경로가 없으므로 속성 이름과 값을 쿼리 문자열 매개 변수로 추가합니다. 페이지가 아닌 페이지에서 실행하면 HomeController누락 된 About조치 방법에 대한 오류가 발생 합니다. 다음을 사용해보십시오.

Html.ActionLink("About", "About", new { controller = "Home" }, new { hidefocus = "hidefocus" })

내가 해결 한 방법은 익명 선언 ( new {}) 전에 네 번째 매개 변수에 null을 추가 하여 다음 메소드 오버로드를 사용하는 것입니다 (linkText, actionName, controllerName, routeValues, htmlAttributes).

Html.ActionLink("About", "About", "Home", null, new { hidefocus = "hidefocus" })

HTMLAttributes 매개 변수를 추가하지 않았습니다.

변경없이 작동합니다.

Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" },null)

ActionLink에 대한 매개 변수가 올바르지 않습니다. 익명 유형 대신 "홈"값을 경로 값으로 사용하려고합니다.

나는 당신이 new { }또는 null마지막 매개 변수로 추가해야한다고 생각합니다 .

편집 : 그냥 게시물을 다시 읽고 마지막이 아닌 두 번째 마지막 매개 변수로 null을 지정하려고한다는 것을 깨달았습니다.


Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" }, new { })

오버로드가 발생합니다 : string linkText, string actionName, string controllerName, Object routeValues, Object htmlAttributes


5 개의 매개 변수가있는 올바른 오버로드 된 방법을 사용하십시오. 예:

@using (@Ajax.BeginForm("Register", "Account", null,
    new AjaxOptions
    {
        HttpMethod = "POST",
        OnSuccess = "OnSuccess",
        OnFailure = "OnFailure",
        OnBegin = "OnBegin",
        OnComplete = "OnComplete"
    }, new { @class = "form-login" }))

코드가 다음과 같이되도록 "홈"(컨트롤러 이름)을 제거하십시오.

Html.ActionLink("About", "About", new { hidefocus = "hidefocus" })

속성 이름으로 :

 @Html.ActionLink(linkText: "SomeText", actionName: "SomeAction", controllerName: "SomeControllerName", routeValues: new { parameterName = parameterValue}, htmlAttributes: null)

Jonathon Watney가 의견에서 지적했듯이 이것은 또한

HTML.BeginForm ()

행동 양식. 내 경우 에는 해당 컨트롤러의 게시 요청 + 작업 만들기를 타겟팅 하는 Create.cshtml에 있었고

using (Html.BeginForm("Create")) {
  @Html.AntiForgeryToken()
  ...
}

렌더링 할 때 쿼리 문자열 "? Length = 6" 을 양식 작업 에 추가했습니다 . roryf의 승인 된 답변에 의해 힌트를 얻고 "Create"의 문자열 길이가 6임을 깨닫고 마침내 명시 적 작업 사양을 제거 하여이 문제를 해결했습니다.

using (Html.BeginForm()) {
      @Html.AntiForgeryToken()
      ...
    }

아마도 다른 사람들도 같은 문제가 있었으며 HTMLAttributes parm을 통해 클래스을 제공해야합니다 . 내 해결책은 다음과 같습니다.

@Html.ActionLink("About", "About", new { controller = "Home", area = "" }, new { hidefocus = "hidefocus", @class = "nav-item nav-link" })

참고 URL : https://stackoverflow.com/questions/824279/why-does-html-actionlink-render-length-4

반응형