简体   繁体   English

使用MVC5 C#和Razor在部分视图中运行javascript

[英]Run javascript in a partial view with MVC5 C# and Razor

I have a small web app in MVC5 and C# using the Razor Engine. 我使用Razor Engine在MVC5和C#中有一个小型Web应用程序。 In my code, I have a main view, which is a index of a table, with some buttons. 在我的代码中,我有一个主视图,它是一个表的索引,带有一些按钮。 When I click one of the buttons a Bootstrap modal appears. 当我单击其中一个按钮时,会出现Bootstrap模式。

So far so good, but the problem is that I want to perform certain actions when buttons on the modal are clicked, but nothing happens. 到目前为止,还不错,但是问题是我想在单击模式上的按钮时执行某些操作,但是什么也没有发生。

This is the main view: 这是主要视图:

    <div id="editModal"></div>
    <a class="btn btn-default editPackage"t itle="Edit Package"><i class="icon-edit"></i></a>
    <h1>Package List</h1>

    <table class="table" id="packagesTable">
        <!-- Big ass table here :D -->
    </table>

This is how I show the modal, by using jQuery: 这就是我使用jQuery显示模态的方式:

 //Show Edit Package modal
    $(".btn.btn-default.editPackage").click(function () {

        $.ajax({
            url: $(this).data('url'),
            type: 'GET',
            cache: false,
            success: function (result) {
                $('#editModal').html(result).find('.modal').modal({
                    show: true
                });
            }
        });
        return false; //prevent browser defualt behavior
    });

So far so good. 到现在为止还挺好。 Everything works fine. 一切正常。 The problem comes with the modal ... 问题来自于模态...

This is the modal: 这是模态:

<div class="modal fade in" id="editPackageModal" tabindex="-1" role="dialog" aria-labelledby="editPackages" aria-hidden="true">
    <div class="modal-dialog" style="overflow-y: auto; max-height: 90vh; height: 80vh;">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title" id="myModalLabel">Edit Package MyPackage</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal">
            <div class="control-group">
              <label class="control-label">Package Name:</label>
              <div class="controls">
                <input type="text" class="form-control" id="package-name" placeholder="MyPackageName">
              </div>
            </div>
            <!-- Other fields here -->
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" id="savePackageChangesBtn">Save changes</button>
        </div>
      </div>
    </div>
  </div>

This is teh Javascript I wish to run when a button in the modal is clicked: 这是我希望在单击模式中的按钮时运行的Javascript:

$(document).ready(function() {
  $("#savePackageChangesBtn").click(function() {
    $('.modal').modal({
      show: true
    });
    return false; //prevent browser defualt behavior
  });
});

The main view is in a file called "Index.cshtml". 主视图位于一个名为“ Index.cshtml”的文件中。 The modal view is a file called "_EditModal.cshtml" (because it is a partial view). 模态视图是一个名为“ _EditModal.cshtml”的文件(因为它是局部视图)。 The javascript code is a file called "custom.js", which is used and runs perfectly fine in the main view. javascript代码是一个名为“ custom.js”的文件,该文件在主视图中使用且运行良好。

Why is this not working? 为什么这不起作用?

Your modal is added dynamically, but your $("#savePackageChangesBtn").click(function() is registered at DOM ready time (when the target element does not exists to bind on). 您的模态是动态添加的,但是$("#savePackageChangesBtn").click(function()在DOM准备就绪时注册(当目标元素不存在要绑定时)。

If you added alert($("#savePackageChangesBtn").length); 如果添加了alert($("#savePackageChangesBtn").length); before the click handler it would return 0. 在点击处理程序之前,它将返回0。

Use a delegated event handler, attached to a non-changing ancestor element. 使用附加到不变祖先元素的委托事件处理程序。

eg 例如

$(document).on('click', "#savePackageChangesBtn", function()

This works by listening for the event to bubble up to a non-changing ancestor, then applies the jQuery selector at event time not event registration time . 通过侦听事件冒泡至一个不变的祖先,然后在事件时间而不是事件注册时间应用jQuery选择器来工作 This means the element only needs to exists when the click occurs. 这意味着仅在单击发生时元素才需要存在。

You would normally choose a non-changing element close to the loaded content, so probably use #editModal instead of document 通常,您会选择一个与加载的内容接近的不变元素,因此可能使用#editModal而不是document

eg 例如

$('#editModal').on('click', "#savePackageChangesBtn", function()

Note: document is the best default if nothing else is convenient, but do not use 'body' as styling can cause it to not respond to bubbled mouse events (eg if the calculated height of the body is zero). 注意:如果没有其他方便的地方, document是最好的默认设置,但是不要使用'body'因为样式可能导致它对冒泡的鼠标事件不响应(例如,如果计算出的body高度为零)。

Either add $("#savePackageChangesBtn").click(function() {}); 要么添加$("#savePackageChangesBtn").click(function() {}); code after you show modal 显示模态后的代码

eg 例如

//Show Edit Package modal
$(".btn.btn-default.editPackage").click(function () {

    $.ajax({
        url: $(this).data('url'),
        type: 'GET',
        cache: false,
        success: function (result) {
            $('#editModal').html(result).find('.modal').modal({
                show: true
            });
            $("#savePackageChangesBtn").click(function () {
                $('.modal').modal({
                    show: true
                });
                return false; //prevent browser defualt behavior
            });
        }
    });
    return false; //prevent browser defualt behavior
});

Or Add the following to your document.ready 或者将以下内容添加到您的文档中。

$(document).on("click", "#savePackageChangesBtn", doSomething);

This makes your document to listen to elements created after init. 这使您的文档可以侦听init之后创建的元素。

And in doSomething add what you want. 然后在doSomething中添加所需的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM