使用布局时如何在视图内添加脚本src [英] how to add script src inside a View when using Layout

查看:81
本文介绍了使用布局时如何在视图内添加脚本src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想包含一个JavaScript参考,例如:

I want to include a javascript reference like:

<script src="@Url.Content("~/Scripts/jqueryFoo.js")" type="text/javascript"></script>

如果我具有Razor视图,那么在不添加到布局中的情况下包括它的正确方法是什么(我仅在单个特定视图中需要它,而并非在所有视图中都需要)

If I have a Razor View, what is the proper way to include this without having to add it to the Layout (I only need it in a single specific View, not all of them)

在aspx中,我们可以使用内容占位符..我在mvc中发现了使用aspx的旧示例,但在Razor视图中却没有..

In aspx, we could use content place holders.. I found older examples using aspx in mvc but not Razor view..

推荐答案

根据您想要实现它的方式(如果在特定位置需要脚本),您可以在_Layout中实现一个@section使您可以从视图本身添加其他脚本,同时仍保留结构.例如

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

<!DOCTYPE html>
<html>
  <head>
    <title>...</title>
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    @RenderSection("Scripts",false/*required*/)
  </head>
  <body>
    @RenderBody()
  </body>
</html>

查看

@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}

否则,您所拥有的就好了.如果您不介意它与所输出的视图内联",则可以在该视图内放置<script>声明.

Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

这篇关于使用布局时如何在视图内添加脚本src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆