Programing

Razor에서 지역 변수를 선언하는 방법?

lottogame 2020. 3. 4. 08:06
반응형

Razor에서 지역 변수를 선언하는 방법?


asp.net mvc 3에서 웹 응용 프로그램을 개발 중입니다. 매우 익숙합니다. 면도기를 사용하는 관점에서 로컬 변수를 선언하고 전체 페이지에서 사용하고 싶습니다. 어떻게 할 수 있습니까?

다음과 같은 작업을 수행하는 것이 사소한 것 같습니다.

@bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
@if (isUserConnected)
{ // meaning that the viewing user has not been saved
    <div>
        <div> click to join us </div>
        <a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
    </div>
}

그러나 이것은 작동하지 않습니다. 이게 가능해?


나는 당신이 꽤 가깝다고 생각합니다, 이것을 시도하십시오 :

@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);}
@if (isUserConnected)
{ // meaning that the viewing user has not been saved so continue
    <div>
        <div> click to join us </div>
        <a id="login" href="javascript:void(0);" style="display: inline; ">join here</a>
    </div>
}

변수가 같은 블록에 있어야한다고 생각합니다.

@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
    if (isUserConnected)
    { // meaning that the viewing user has not been saved
        <div>
            <div> click to join us </div>
            <a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
        </div>
    }
    }

다음을 사용할 수도 있습니다.

@if(string.IsNullOrEmpty(Model.CreatorFullName))
{
...your code...
}

코드에서 변수가 필요 없음


코드 루프가 증가함에 따라 int 변수를 찾고 있다면 다음과 같이 사용할 수 있습니다.

@{
  int counter = 1;

  foreach (var item in Model.Stuff) {
    ... some code ...
    counter = counter + 1;
  }
} 

OP의 문제에 대한 직접적인 대답은 아니지만 도움이 될 수도 있습니다. 범위 내에서 일부 HTML 옆에 로컬 변수를 문제없이 선언 할 수 있습니다.

@foreach (var item in Model.Stuff)
{
    var file = item.MoreStuff.FirstOrDefault();

    <li><a href="@item.Source">@file.Name</a></li>
}

페이지에서 액세스 할 var를 선언하려면 .... 페이지 상단이 일반적으로 작동합니다. 암시 적 또는 명시 적 선택.

          @{
               //implicit
               var something1 = "something";
               //explicit
               string something2 = "something";
          }


            @something1 //to display on the page
            @something2 //to display on the page

참고 URL : https://stackoverflow.com/questions/6601715/how-to-declare-a-local-variable-in-razor



반응형