programing

레이저를 사용하여 자바스크립트 변수에 부울을 렌더링하려면 어떻게 해야 합니까?

codeshow 2023. 10. 24. 21:37
반응형

레이저를 사용하여 자바스크립트 변수에 부울을 렌더링하려면 어떻게 해야 합니까?

cshtml 파일의 자바스크립트 변수에 부울을 렌더링하려면 어떻게 해야 합니까?

현재 구문 오류가 표시됩니다.

<script type="text/javascript" >

    var myViewModel = {
        isFollowing: @Model.IsFollowing  // This is a C# bool
    };
</script>

다음을 시도해 볼 수도 있습니다.

isFollowing: '@(Model.IsFollowing)' === '@true'

그리고 더 좋은 방법은 다음을 사용하는 것입니다.

isFollowing: @Json.Encode(Model.IsFollowing)

ASP에서 날 데려왔으니까요NET Core,IJsonHelper없어요Encode()방법.대신 사용Serialize(). 예:

isFollowing: @Json.Serialize(Model.IsFollowing)    

JSON 부울은 소문자여야 합니다.

따라서 이 방법을 사용해 보십시오(그리고 반드시 다음 방법을 사용하십시오).//줄에 댓글 달기):

var myViewModel = {
    isFollowing: @Model.IsFollowing.ToString().ToLower()
};

또는(참고: 네임스페이스를 사용해야 합니다.System.Xml):

var myViewModel = {
    isFollowing: @XmlConvert.ToString(Model.IsFollowing)
};
var myViewModel = {
    isFollowing: '@(Model.IsFollowing)' == "True";
};

왜죠True아닌true당신이 묻는다면...좋은 질문:
부울은 왜 그럴까요.ToString 출력 "True"가 아닌 "True"입니다.

보다 읽기 쉬운 해결책은 다음과 같습니다.

isFollowing: @(Model.IsFollowing ? "true" : "false")

부울로의 변환을 사용하여 고려해야 할 다른 옵션이 있습니다.

isFollowing: !!(@Model.IsFollowing ? 1 : 0)

이렇게 하면 클라이언트 측에서 다음과 같이 생성되며, 1은 true로, 0은 false로 변환됩니다.

isFollowing: !!(1)  -- or !!(0)

변환 작업 정의 및 재정의 추가.ToString()많은 일을 절약할 수 있습니다.

정의하기struct프로젝트에서:

/// <summary>
/// A <see cref="bool"/> made for use in creating Razor pages.
/// When converted to a string, it returns "true" or "false".
/// </summary>
public struct JSBool
{
    private readonly bool _Data;

    /// <summary>
    /// While this creates a new JSBool, you can also implicitly convert between the two.
    /// </summary>
    public JSBool(bool b)
    {
        _Data = b;
    }

    public static implicit operator bool(JSBool j) => j._Data;
    public static implicit operator JSBool(bool b) => new JSBool(b);

    // Returns "true" or "false" as you would expect
    public override string ToString() => _Data.ToString().ToLowerInvariant();
}

사용.

C#를 직접 캐스팅 할 수 있습니다.bool, 질문의 경우와 마찬가지로:

{
    // Results in `isFollowing : true`
    isFollowing : @((JSBool)Model.IsFollowing)
}

하지만 당신은 또한 a를 사용할 수 있습니다.JSBool레이저 코드에 직접적으로 표시되어 있습니다.true그리고.false별도의 작업을 하지 않아도 됩니다.

@{
    JSBool isA = true;
    JSBool isB = false;
    // Standard boolean operations work too:
    JSBool isC = a || b;
}

<script>
    if (@isC)
        console.log('true');
</script>

이것은 위에서 정의한 암묵적 변환 연산자 때문에 작동합니다.


레이저 코드에 사용하려는 경우에만 이 코드를 사용해야 합니다.즉, 코드가 지저분해질 수 있으므로 일반적인 C#에서는 사용하지 마십시오.

언급URL : https://stackoverflow.com/questions/14448604/using-razor-how-do-i-render-a-boolean-to-a-javascript-variable

반응형