Javascript 如何将java脚本移动到自定义文件,然后从MVC应用程序调用它?

Javascript 如何将java脚本移动到自定义文件,然后从MVC应用程序调用它?,javascript,jquery,asp.net-mvc-4,Javascript,Jquery,Asp.net Mvc 4,我需要将一个脚本(打开一个模式窗口)从视图内部移动到一个自定义脚本文件中,但我需要一些帮助 这是索引视图的一部分: <div class=""> <button id="showModal">Click Me</button> </div> div id="theModal" class="modal fade"> <div class="modal-dialog"> // Code

我需要将一个脚本(打开一个模式窗口)从视图内部移动到一个自定义脚本文件中,但我需要一些帮助

这是索引视图的一部分:

<div class="">
    <button id="showModal">Click Me</button>
</div>

div id="theModal" class="modal fade">
    <div class="modal-dialog">
       // Code
       ...
    </div>
</div>

@section Scripts {
    <script>
        $(function () {
            var showModal = function () {
                $("#theModal").modal("show");
            };
            $("#showModal").click(showModal);
        });
    </script>
}

点击我
div id=“模态”class=“模态衰减”>
//代码
...
@节脚本{
$(函数(){
var showModal=函数(){
元(“#theModal”).modal(“show”);
};
$(“#showmodel”)。单击(showmodel);
});
}

我知道我需要在button OnClick事件中调用函数并添加对脚本文件的引用,但问题是:将脚本作为函数写入文件、传递参数以及如何从单击按钮正确调用它的正确方法是什么?

将其放入外部javascript文件中(并在视图中引用),将确保在按钮上设置单击处理程序


您希望传递给此事件的参数类型是什么?您希望从中得到什么?

您标记了MVC 4,因此我假设您将使用捆绑程序

首先确保您创建的脚本文件位于捆绑包中,查找
BundleConfig.cs
并为新文件添加捆绑包:

bundles.Add(new ScriptBundle("~/bundles/myBundle").Include(
  "~/Scripts/sample.js"));
那么在你看来,

@Scripts.Render(
    "~/bundles/myBundle")
<script>
$(function () {
    $('#showModal').on('click', function () {
        showAlert();
    });
});
</script>
以下是所要求的具体示例:

假设一个名为
sample.js
的文件包含以下内容:

showAlert = function(){
     alert('hey an alert!);
};
在你看来:

@Scripts.Render(
    "~/bundles/myBundle")
<script>
$(function () {
    $('#showModal').on('click', function () {
        showAlert();
    });
});
</script>

$(函数(){
$('#showmodel')。在('click',函数(){
showarert();
});
});
这将添加
showAlert
作为单击showModal锚的事件处理程序