개발관련/other

Razor에서 삼항 연산자를 사용하는 방법 (특히 HTML 속성에서)

Rateye 2021. 7. 20. 10:42
728x90
반응형

 

질문 : Razor에서 삼항 연산자를 사용하는 방법 (특히 HTML 속성에서)?

WebForms 뷰 엔진을 사용하면 특히 HTML 속성 내에서 매우 간단한 조건에 대해 삼항 연산자를 일반적으로 사용합니다. 예를 들면 :

<a class="<%=User.Identity.IsAuthenticated ? "auth" : "anon" %>">My link here</a>

위의 코드는 사용자가 인증되었는지 여부에 따라 <a> auth 또는 anon 클래스를 제공합니다.

Razor 뷰 엔진과 동등한 구문은 무엇입니까? Razor는 코드와 마크 업에 들어가고 나올 때를 "알기"위해 HTML 태그가 필요하기 때문에 현재 다음과 같은 문제가 있습니다.

@if(User.Identity.IsAuthenticated)  { <a class="auth">My link here</a> }
else { <a class="anon">My link here</a> }

이것은 가볍게 말하면 끔찍 합니다.

나는 이와 같은 일을하고 싶지만 Razor에서 방법을 이해하는 데 어려움을 겪고 있습니다.

<a class="@=User.Identity.IsAuthenticated ? "auth" : "anon";">My link here</a>

-

최신 정보:

그 동안 저는이 HtmlHelper를 만들었습니다.

public static MvcHtmlString Conditional(this HtmlHelper html, Boolean condition, String ifTrue, String ifFalse)
{
  return MvcHtmlString.Create(condition ? ifTrue : ifFalse);
}

Razor에서 다음과 같이 호출 할 수 있습니다.

<a class="@Html.Conditional(User.Identity.IsAuthenticated, "auth", "anon")">My link here</a>

그래도 확장 메서드에서 래핑하지 않고 삼항 연산자를 사용하는 방법이 있기를 바랍니다.

답변

@() 표현식 구문을 사용할 수 있어야합니다.

<a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a>
  
출처 : https://stackoverflow.com/questions/4091831/how-to-use-ternary-operator-in-razor-specifically-on-html-attributes
728x90
반응형