将 JavaScript 放在部分视图中可以吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11098198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:26:55  来源:igfitidea点击:

Is it OK to put JavaScript in Partial Views

javascriptasp.net-mvcrazorpartial-views

提问by Tomy

I'm working on the web app where the main page contains two parts: the constant block which is always visible and the info-block made up by one of 3 partial views. Each of the partial views appears as a result of AJAX request and is loaded just once (after that switching windows is provided by jquery). It works well but I've faced with one problem.

我正在开发 Web 应用程序,其中主页包含两部分:始终可见的常量块和由 3 个部分视图之一组成的信息块。每个部分视图都作为 AJAX 请求的结果出现并且只加载一次(之后切换窗口由 jquery 提供)。它运作良好,但我遇到了一个问题。

The html-code of partial views contains js functions that are used in the constant block and in the info-block as well. When the page is loaded, these functions can “see” each other and it works but resharper can't find function declarations and warn me about this. I can't solve the problem by transferring them into external js file because of razor syntax which can be found in their code.

局部视图的 html 代码包含在常量块和信息块中使用的 js 函数。当页面加载时,这些函数可以“看到”彼此并且可以工作,但是 resharper 找不到函数声明并警告我这一点。由于可以在他们的代码中找到 razor 语法,我无法通过将它们传输到外部 js 文件来解决问题。

What can I do with this?

我能用这个做什么?

Thanks.

谢谢。

Update:

更新:

Finally I've decided to solve the problem separating my js code from views. So the new question was how to include razor syntax into js files or what is the acceptable alternative. The popular solutions I've found are using global variables, data attributes and the one I like more – RazorJS library by John Katsiotis.

最后我决定解决将我的 js 代码与视图分开的问题。所以新的问题是如何将 razor 语法包含到 js 文件中,或者什么是可接受的替代方案。我发现的流行解决方案是使用全局变量、数据属性和我更喜欢的一个——John Katsiotis 的 RazorJS 库。

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

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

I hope it's going to work stable and make Resharper happy.

我希望它能够稳定运行并让 Resharper 满意。

Cheers!

干杯!

Update:

更新:

After 3 years I recalled this question and decided to update it according to my experience. In fact now I would rather not recommend using additional libraries for that. Especially if you are not the only member in the project team… It is much better if you are ensured in all of your libraries, they are supported by creator and community and can be easily integrated into your IDE (if use special syntax for example). Also all the guys from your team should be aware of how does it work. So now I would suggest doing the next things:

3年后,我想起了这个问题,并决定根据我的经验更新它。事实上,现在我宁愿不建议为此使用额外的库。特别是如果您不是项目团队中的唯一成员……如果您在所有库中都得到保证,它们会得到创建者和社区的支持,并且可以轻松集成到您的 IDE 中(例如,如果使用特殊语法),那就更好了. 此外,您团队中的所有人员都应该知道它是如何工作的。所以现在我建议做以下事情:

  1. Hold all the JS in separate files. Isolate it as much as you can. Provide the external API for it.
  2. Call the API functions from your Views.
  3. Pass all the Razor generated URLs, text messages, constants as resource parameter.
  1. 将所有 JS 保存在单独的文件中。尽可能地隔离它。为其提供外部 API。
  2. 从您的视图调用 API 函数。
  3. 将所有 Razor 生成的 URL、文本消息、常量作为资源参数传递。

For example:

例如:

js file:

js文件:

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

View:

看法:

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

采纳答案by Wahid Bitar

If Resharper warns you it's not a big deal ^_^

如果 Resharper 警告你这没什么大不了的^_^

But if I were you I wouldn't put JavaScript in the partial view at all.

但如果我是你,我根本不会把 JavaScript 放在局部视图中

Because the partial view could be inserted in one page many times then you'll get an issues with your JavaScripts.

因为部分视图可以在一个页面中多次插入,所以您的 JavaScript 会出现问题。

And for your case if you couldn't separate the JavaScript to JS file then just create another PartialView and put these scripts in it and just render it in your main page.

对于您的情况,如果您无法将 JavaScript 与 JS 文件分开,那么只需创建另一个 PartialView 并将这些脚本放入其中,然后将其呈现在您的主页中。

回答by codenheim

If you want to write partial views that are encapsulated "widgets" that just work once you include them in a page, then embedding a script block inside the partial view is one clean way to wrap the markup and the initialization script together in a partial view. For example, I might have a partial view named "_EventList" that I use throughout my site. If I place in two places on my master page it should just work and I prefer not to have to write logic in my master page to initialize the widget.

如果您想编写封装“小部件”的局部视图,一旦将它们包含在页面中就可以工作,那么在局部视图中嵌入脚本块是将标记和初始化脚本包装在一起的一种干净的方法在局部视图中. 例如,我可能有一个名为“_EventList”的局部视图,我在整个站点中使用它。如果我在我的母版页上放置两个位置,它应该可以正常工作,而且我不想在我的母版页中编写逻辑来初始化小部件。

If you will never use it more than once in a page, its simple. But if you might, then wrap the script so it doesn't execute twice. See below. For the sake of Stack Overflow snippets I simulate it by repeating the partial view twice in the code snippet to represent including a partial view twice in a master page.

如果您永远不会在一个页面中多次使用它,这很简单。但是,如果可以,请包装脚本,使其不会执行两次。见下文。为了堆栈溢出片段,我通过在代码片段中重复局部视图两次来模拟它,以表示在母版页中包含局部视图两次。

My master page might look like:

我的母版页可能如下所示:

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

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

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

Example:

例子:

<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 -->

回答by eaglestorm

I agree with Wahid that you shouldn't put JavaScript in views at all partial or otherwise. I've seen enough code that does this to know it only leads to no good.

我同意 Wahid 的观点,你不应该将 JavaScript 放在视图中,无论是局部的还是其他的。我已经看到足够多的代码来知道它只会导致不好。

I would also say that you should be able to transfer the logic encapsulated in the Razor syntax into the JavaScript, you just need to pass to your JavaScript the information needed by your logic.

我还想说,您应该能够将封装在 Razor 语法中的逻辑传输到 JavaScript 中,您只需要将逻辑所需的信息传递给 JavaScript。

I'm just guessing from experience with this next comment but you should design the JavaScript the same way you would design the structure of your C# or VB.NET code. That way the logic that you are using Razor for should be part of your JavaScript.

我只是根据下一条评论的经验进行猜测,但您应该像设计 C# 或 VB.NET 代码的结构一样设计 JavaScript。这样你使用 Razor 的逻辑应该是你的 JavaScript 的一部分。

That way your JavaScript will be easier to maintain and I assume Resharper should also be happier.

这样你的 JavaScript 会更容易维护,我认为 Resharper 也应该更快乐。

回答by Bon

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

我这样做并发现它非常方便。在 ViewBag、HttpContext 等可用的情况下,动态加载部分 javascript 片段非常有效。

It results in something that feels like using T4 templates.

它会产生类似于使用 T4 模板的感觉。

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

如果您添加这样的幻像脚本标签,您甚至可以获得 javascript 验证、智能感知等。

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

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

回答by eaglei22

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).

我遇到的问题是在调试过程中,有时我无法让我的断点命中并且无法解决问题,除非我将脚本移到父视图。很可能是由于多次打印该函数。我希望部分能够更好地解决和组织这个问题,但是部分视图不支持部分(至少在 MVC 4 中不支持)。

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

所以我的回答是为了维护和调试,不应该在局部视图中放置任何脚本。