Development Tip

부분보기에 JavaScript를 넣어도 괜찮습니까?

yourdevel 2020. 12. 5. 10:46
반응형

부분보기에 JavaScript를 넣어도 괜찮습니까?


메인 페이지에 항상 표시되는 상수 블록과 3 개의 부분보기 중 하나로 구성된 정보 블록의 두 부분이 포함 된 웹 앱에서 작업 중입니다. 각 부분보기는 AJAX 요청의 결과로 나타나며 한 번만로드됩니다 (이후 jquery에서 창 전환이 제공됨). 잘 작동하지만 한 가지 문제에 직면했습니다.

부분 뷰의 html 코드에는 상수 블록과 정보 블록에서도 사용되는 js 함수가 포함되어 있습니다. 페이지가로드되면 이러한 함수는 서로 "볼"수 있고 작동하지만 resharper는 함수 선언을 찾을 수 없으며 이에 대해 경고합니다. 코드에서 찾을 수있는 면도기 구문 때문에 외부 js 파일로 전송하여 문제를 해결할 수 없습니다.

이것으로 무엇을 할 수 있습니까?

감사.

최신 정보:

마지막으로 내 js 코드를 뷰에서 분리하는 문제를 해결하기로 결정했습니다. 그래서 새로운 질문은 js 파일에 razor 구문을 포함하는 방법 또는 허용 가능한 대안이 무엇인지였습니다. 내가 찾은 인기있는 솔루션은 전역 변수, 데이터 속성 및 내가 더 좋아하는 John Katsiotis의 RazorJS 라이브러리를 사용하는 것입니다.

http://djsolid.net/blog/razorjs---write-razor-inside-your-javascript-files

안정적으로 작동하고 Resharper를 행복하게 만들기를 바랍니다.

건배!

최신 정보:

3 년 후 저는이 질문을 떠올려 제 경험에 따라 업데이트하기로 결정했습니다. 사실 지금은 추가 라이브러리를 사용하지 않는 것이 좋습니다. 특히 여러분이 프로젝트 팀의 유일한 구성원이 아니라면… 모든 라이브러리에서 보장되는 것이 훨씬 낫습니다. 라이브러리는 제작자와 커뮤니티에서 지원하고 IDE에 쉽게 통합 할 수 있습니다 (예 : 특수 구문을 사용하는 경우). . 또한 팀원 모두가 어떻게 작동하는지 알고 있어야합니다. 이제 다음 작업을 제안합니다.

  1. 모든 JS를 별도의 파일에 보관하십시오. 가능한 한 많이 분리하십시오. 이를위한 외부 API를 제공하십시오.
  2. 뷰에서 API 함수를 호출합니다.
  3. Razor에서 생성 한 모든 URL, 텍스트 메시지, 상수를 리소스 매개 변수로 전달합니다.

예를 들면 :

Node.js 파일 :

$.api.someInitFunction = function(resources){ ... }

전망:

<script>
    $.api.someInitFunction({
        urls: { myAction: '@Url.Action("MyAction", "MyController")' },
        messages: { error: '@errorMessage' },
        consts: { myConst: @myIntConst }
    });
</script>

Resharper가 경고하면 큰 문제가 아닙니다 ^ _ ^

하지만 내가 당신이라면 자바 스크립트를 부분보기에 전혀 넣지 않을 것 입니다.

부분보기가 한 페이지에 여러 번 삽입 될 수 있으므로 JavaScript에 문제가 발생합니다.

그리고 귀하의 경우 JavaScript를 JS 파일로 분리 할 수 ​​없다면 다른 PartialView를 만들고이 스크립트를 그 안에 넣고 메인 페이지에서 렌더링하십시오.


페이지에 포함 된 후에 만 ​​작동하는 캡슐화 된 "위젯"인 부분보기를 작성하려는 경우 부분보기에 스크립트 블록을 포함하는 것은 부분보기에서 마크 업과 초기화 스크립트를 함께 래핑하는 깔끔한 방법 중 하나입니다. . 예를 들어 내 사이트 전체에서 사용하는 "_EventList"라는 부분보기가있을 수 있습니다. 마스터 페이지의 두 곳에 배치하면 제대로 작동해야하며 위젯을 초기화하기 위해 마스터 페이지에 로직을 작성하지 않아도됩니다.

한 페이지에서 두 번 이상 사용하지 않을 경우 간단합니다. 그러나 가능하다면 두 번 실행되지 않도록 스크립트를 래핑하십시오. 아래를 참조하십시오. Stack Overflow 스 니펫을 위해 코드 스 니펫에서 부분보기를 두 번 반복하여 마스터 페이지에 부분보기를 두 번 포함하는 것을 나타냅니다.

내 마스터 페이지는 다음과 같습니다.

<div id="left-nav">
   @Html.Partial("_EventList")           
</div>

<div id="body">
</div>

<div id="right-nav">
   @Html.Partial("_EventList")
</div>

예:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Self-contained partial view containing widget -->

<div id="widgetDiv" class="panel panel-default">

    <div class="panel-heading">Event Dates</div>
    <div class="panel panel-group">
       <ul class="widget">
         <!-- These will load dynamically -->
       </ul>
    </div>

    <script>
        $(document).ready(function() {

            // Run this once only in case widget is on page more than once
            if(typeof $widget == 'undefined') {
                $widget = $("ul.widget"); // could be more than one
                // mock data to simulate an ajax call
                var data = [
                   {Description: "March", StartDate: "03/01/2015"},
                   {Description: "April", StartDate: "04/01/2015"},
                   {Description: "May", StartDate: "05/01/2015"}
                ];

                $.each($widget, function(w, widget) {
                    // might be an $.ajax call
                    $.each(data, function(i, row) {
                        $(widget).append("<li><a href='/Widget/Search?startDate=" + row.StartDate + "'>" + row.Description + "</a></li>");
                    });
                });
            }
        });
    </script>
</div>
<!-- End of widget / partial view -->



<!-- Second copy of above for sake of example snippet -->
<!-- No need to read further -->









<!-- Self-contained partial view containing widget -->

<div id="widgetDiv" class="panel panel-default">

    <div class="panel-heading">Event Dates</div>
    <div class="panel panel-group">
       <ul class="tinylist nav nav-sidebar widget">
         <!-- These will load dynamically -->
       </ul>
    </div>

    <script>
        $(document).ready(function() {

            // Run this once only in case widget is on page more than once
            if(typeof $widget == 'undefined') {
                $widget = $("ul.widget"); // could be more than one
                // mock data to simulate an ajax call
                var data = [
                   {Description: "March", StartDate: "03/01/2015"},
                   {Description: "April", StartDate: "04/01/2015"},
                   {Description: "May", StartDate: "05/01/2015"}
                ];

                $.each($widget, function(w, widget) {
                    // might be an $.ajax call
                    $.each(data, function(i, row) {
                        $(widget).append("<li><a href='/Widget/Search?startDate=" + row.StartDate + "'>" + row.Description + "</a></li>");
                    });
                });
            }
        });
    </script>
</div>
<!-- End of widget / partial view -->


Wahid에 동의합니다. 뷰에 자바 스크립트를 부분적으로 또는 다른 방식으로 삽입해서는 안됩니다. 나는 이것이 좋지 않다는 것을 알기 위해 이것을 수행하는 코드를 충분히 보았다.

또한 Razor 구문에 캡슐화 된 논리를 JavaScript로 전송할 수 있어야하며 논리에 필요한 정보를 JavaScript에 전달하기 만하면됩니다.

이 다음 주석에 대한 경험에서 추측하고 있지만 C # 또는 VB.NET 코드의 구조를 설계하는 것과 동일한 방식으로 JavaScript를 설계해야합니다. 이렇게하면 Razor를 사용하는 논리가 JavaScript의 일부가되어야합니다.

그렇게하면 JavaScript를 유지하기가 더 쉬울 것이며 Resharper도 더 행복해야한다고 생각합니다.


I do this and find it highly convenient. It works well to dynamically load partial javascript snippets with the availability of ViewBag, HttpContext, etc.

It results in something that feels like using T4 templates.

You can even get javascript validation, intellisense, etc if you add phantom script tags like this.

@using System.Configuration
@if (false)
{
    @:<script type="text/javascript">
}    
        $scope.clickCartItem = function(cartItem) {
            console.log(cartItem);
            window.location.href =@Html.Raw("('" + ConfigurationManager.AppSettings["baseUrl"] + "/Checkout/' + cartItem.ItemId)");
        };
        dataAccess.getCart(
        function (response) {
            //...
        },
        function (response) {
            //...
        }
        );

@if (false)
{
    @:</script>
}

For future viewers of this question, here is my experience. I thought it would be a good idea to keep the scripts that were only used by the partial in the partial for organization.

The issue I had was during debugging, I sometimes would have trouble getting my breakpoints to hit and wouldn't be able to troubleshoot an issue unless I moved the script to the parent view. Most likely due to printing the function more than once. I was hoping sections would solve and organize this better, but sections are not supported in partial views (at least not in MVC 4).

So my answer would be for the sake of maintenance and debugging, no scripts should not be put inside partial views.

참고URL : https://stackoverflow.com/questions/11098198/is-it-ok-to-put-javascript-in-partial-views

반응형