【问题标题】:inject javascript in cshtml from partial-view using RenderSection not working使用 RenderSection 从部分视图中注入 cshtml 中的 javascript 不起作用
【发布时间】:2012-11-06 18:13:39
【问题描述】:

我有一个局部视图,需要在页面底部添加一些 javascript。

主页:

...some html...
<div>
@Html.Partial("_myPartial")
</div>

....more html....

//required JS at BOTTOM -  THIS should also come from above partial
@RenderSection("scripts", required: false)

我的部分观点:

<div id="Slider">
    <img src="http://placehold.it/1000x400&text=[img 1]" />
    <img src="http://placehold.it/1000x400&text=[img 2]" />
    <img src="http://placehold.it/1000x400&text=[img 3]" />
    <img src="http://placehold.it/1000x400&text=[img 4]" />
</div>


@section scripts
{
 <script type="text/javascript">
  $(window).load(function () {
    $('#Slider').orbit();
  });
  </script>
}

但这不起作用 - 脚本部分不包括在内。

我用谷歌搜索过,不支持这个……嗯……

...您将如何处理这种情况??

建议在脚本中再制作一个部分,并包括这个...... 不漂亮!

有更好的方法吗?

谢谢!

【问题讨论】:

    标签: asp.net-mvc razor


    【解决方案1】:

    查看渲染页面的来源。是不是你的脚本在定义jQuery之前就出来了?

    您的默认 _Layout.cshtml 可能有...

    <!DOCTYPE html>
    <html lang="en">
    ...
    @RenderBody()
    ...
    @Scripts.Render("~/bundles/scripts")
    @RenderSection("scripts", required:false)
    ...
    </html>
    

    您需要告诉 MVC 将您的脚本放在脚本包之后。在您的 DoStuff.cshtml 中,

    ...
    @using (Html.BeginForm()){ //this bit is in the body of the page 
        @Html.TextBoxFor(m=>m.NewSalary)
        <input type="submit" data-confirmprompt='are you sure?' />
    }
    ...
    
    @section scripts{ //this bit will end up in the scripts section
    <script type="text/javascript">
        //http://blogs.msdn.com/b/stuartleeks/archive/2010/12/16/using-asp-net-mvc-and-jquery-to-create-confirmation-prompts.aspx
        //cunning script so you can say 
    
        $(document).ready(function () {
            $('*[data-confirmprompt]').click(function (event) {
                var promptText = $(this).attr('data-confirmprompt');
                if (!confirm(promptText)) {
                    event.preventDefault();
                }
            });
        });
    </script>
    }
    

    【讨论】:

      【解决方案2】:

      您可以将它包含在您的部分中,然后它将被执行,省略$(window).load

      <div id="Slider">
          <img src="http://placehold.it/1000x400&text=[img 1]" />
          <img src="http://placehold.it/1000x400&text=[img 2]" />
          <img src="http://placehold.it/1000x400&text=[img 3]" />
          <img src="http://placehold.it/1000x400&text=[img 4]" />
      </div>
      
      
       <script type="text/javascript">
          $('#Slider').orbit();
        </script>
      

      【讨论】:

      • 你好,我试过了,但没有成功:只是JS没有添加到页面中,因此没有执行。
      猜你喜欢
      • 1970-01-01
      • 2011-12-17
      • 2017-05-18
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      相关资源
      最近更新 更多