Ben Junior
Ben Junior

Reputation: 2589

How to move a java script to a custom file then call it from MVC app?

I need to move a script (that opens a modal window), from inside the view into a custom script file, but I need some help with it.

This is part of the Index view:

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

I know that I need to hoop up the function in the button OnClick event and add a reference to the script file, but the question is: What is the correct way to write the script as a function in the file, pass the arguments and how to properly call it from the click button?

Upvotes: 2

Views: 652

Answers (2)

Maess
Maess

Reputation: 4146

You tagged MVC 4 so I assume you will use the bundler.

First make sure the script file you created is in a bundle, look for BundleConfig.cs and add a bundle for your new file:

bundles.Add(new ScriptBundle("~/bundles/myBundle").Include(
  "~/Scripts/sample.js"));

Then in your view:

@Scripts.Render(
    "~/bundles/myBundle")

Here is the requested concrete example:

Assume a file called sample.js with the following content:

showAlert = function(){
     alert('hey an alert!);
};

In your view:

<script>
$(function () {
    $('#showModal').on('click', function () {
        showAlert();
    });
});
</script>

This will add showAlert as the event handler for the click of the showModal anchor.

Upvotes: 2

rwisch45
rwisch45

Reputation: 3702

Putting this in your external javascript file (and referencing it in your view), will ensure the click handler gets set on the button. jQuery docs

$(function () {
    $('#showModal').on('click', function () {
        $("#theModal").modal("show");
    });
});

What type of arguments did you want to pass to this event? What do you want to get back from it?

Upvotes: 1

Related Questions